diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs new file mode 100644 index 000000000..25a899c52 --- /dev/null +++ b/crates/horizon-client/src/effects.rs @@ -0,0 +1,303 @@ +//! Player status effects (`MobEffectInstance` / `LivingEntity.activeEffects`): +//! add/update with hidden effects, per-tick application of the periodic +//! effects (regeneration, poison, wither, hunger, saturation, instant +//! effects), and the derived flags the movement and damage code read. +use crate::brewing; + +#[derive(Clone, Debug, PartialEq)] +pub struct EffectInstance { + /// Effect id without namespace (`speed`, `poison`, ...). + pub id: &'static str, + /// Remaining ticks; -1 is infinite. + pub duration: i32, + pub amplifier: i32, + pub ambient: bool, + pub visible: bool, + pub hidden: Option>, +} +impl EffectInstance { + pub fn new(id: &'static str, duration: i32, amplifier: i32) -> Self { + Self { id, duration, amplifier: amplifier.clamp(0, 255), ambient: false, visible: true, hidden: None } + } + fn infinite(&self) -> bool { + self.duration == -1 + } + fn shorter_than(&self, other: &Self) -> bool { + !self.infinite() && (self.duration < other.duration || other.infinite()) + } + /// `MobEffectInstance.update`. + pub fn update(&mut self, take: &Self) -> bool { + let mut changed = false; + if take.amplifier > self.amplifier { + if take.shorter_than(self) { + let previous = self.hidden.take(); + let mut copy = self.clone(); + copy.hidden = previous; + self.hidden = Some(Box::new(copy)); + } + self.amplifier = take.amplifier; + self.duration = take.duration; + changed = true; + } else if self.shorter_than(take) { + if take.amplifier == self.amplifier { + self.duration = take.duration; + changed = true; + } else if let Some(h) = self.hidden.as_mut() { + h.update(take); + } else { + self.hidden = Some(Box::new(EffectInstance { hidden: None, ..take.clone() })); + } + } + if !take.ambient && self.ambient || changed { + self.ambient = take.ambient; + changed = true; + } + if take.visible != self.visible { + self.visible = take.visible; + changed = true; + } + changed + } + fn tick_down(&mut self) { + if let Some(h) = self.hidden.as_mut() { + h.tick_down(); + } + if !self.infinite() { + self.duration -= 1; + } + } + fn downgrade(&mut self) { + if self.duration == 0 + && let Some(h) = self.hidden.take() + { + let h = *h; + self.duration = h.duration; + self.amplifier = h.amplifier; + self.ambient = h.ambient; + self.visible = h.visible; + self.hidden = h.hidden; + } + } +} +/// What an effect tick asks the game to do to the player. +#[derive(Clone, Debug, PartialEq)] +pub enum EffectAction { + Heal(f32), + /// Damage with a damage type id (`minecraft:magic`, `minecraft:wither`). + Hurt(&'static str, f32), + Exhaust(f32), + /// FoodData.eat(nutrition, saturation modifier). + Eat(i32, f32), +} +/// `shouldApplyEffectTickThisTick` + `applyEffectTick` for the periodic effects. +fn periodic(id: &str, tick: i32, amp: i32) -> Option { + let every = |base: i32| { + let interval = base >> amp; + interval <= 0 || tick % interval == 0 + }; + match id { + "regeneration" if every(50) => Some(EffectAction::Heal(1.0)), + "poison" if every(25) => Some(EffectAction::Hurt("minecraft:magic", 1.0)), + "wither" if every(40) => Some(EffectAction::Hurt("minecraft:wither", 1.0)), + "hunger" => Some(EffectAction::Exhaust(0.005 * (amp + 1) as f32)), + "saturation" if tick >= 1 => Some(EffectAction::Eat(amp + 1, 1.0)), + "instant_health" if tick >= 1 => Some(EffectAction::Heal((4 << amp.min(30)) as f32)), + "instant_damage" if tick >= 1 => Some(EffectAction::Hurt("minecraft:magic", (6 << amp.min(30)) as f32)), + _ => None, + } +} +/// `InstantenousMobEffect.applyInstantenousEffect` (potions apply these directly). +pub fn instant(id: &str, amp: i32, scale: f64) -> Option { + match id { + "instant_health" => Some(EffectAction::Heal((scale * f64::from(4 << amp.min(30))) as i32 as f32)), + "instant_damage" => Some(EffectAction::Hurt("minecraft:magic", (scale * f64::from(6 << amp.min(30))) as i32 as f32)), + "saturation" => Some(EffectAction::Eat(amp + 1, 1.0)), + _ => None, + } +} +#[derive(Clone, Debug, Default)] +pub struct PlayerEffects { + pub list: Vec, + pub tick_count: i32, +} +impl PlayerEffects { + pub fn get(&self, id: &str) -> Option<&EffectInstance> { + self.list.iter().find(|e| e.id == id) + } + pub fn amplifier(&self, id: &str) -> Option { + self.get(id).map(|e| e.amplifier) + } + /// `LivingEntity.addEffect`; returns whether anything changed. + pub fn add(&mut self, effect: EffectInstance) -> bool { + match self.list.iter_mut().find(|e| e.id == effect.id) { + Some(existing) => existing.update(&effect), + None => { + self.list.push(effect); + true + } + } + } + pub fn clear(&mut self) { + self.list.clear(); + } + /// `LivingEntity.tickEffects` (server part): actions to apply, in order. + pub fn tick(&mut self) -> Vec { + self.tick_count = self.tick_count.wrapping_add(1); + let mut actions = Vec::new(); + let tick_count = self.tick_count; + self.list.retain_mut(|e| { + if !(e.infinite() || e.duration > 0) { + return false; + } + let t = if e.infinite() { tick_count } else { e.duration }; + if let Some(a) = periodic(e.id, t, e.amplifier) { + actions.push(a); + } + e.tick_down(); + e.downgrade(); + e.infinite() || e.duration > 0 + }); + actions + } + /// Effects applied by drinking a potion (`PotionContents.applyToLivingEntity`). + pub fn potion_effects(potion: Option<&str>, scale: f32) -> (Vec, Vec) { + let mut lasting = Vec::new(); + let mut now = Vec::new(); + if let Some(def) = potion.and_then(brewing::potion) { + for (id, duration, amp) in def.effects { + let id = brewing::effect(id).map_or("speed", |e| e.id); + if brewing::effect(id).is_some_and(|e| e.instant) { + now.extend(instant(id, *amp, 1.0)); + } else { + // withScaledDuration: max(floor(d * scale), 1). + let d = ((*duration as f32) * scale).floor() as i32; + lasting.push(EffectInstance::new(id, d.max(1), *amp)); + } + } + } + (lasting, now) + } + /// Flags for movement and damage code. + pub fn status(&self) -> StatusFlags { + StatusFlags { + jump_boost: self.amplifier("jump_boost"), + slow_falling: self.get("slow_falling").is_some(), + levitation: self.amplifier("levitation"), + resistance: self.amplifier("resistance"), + fire_resistance: self.get("fire_resistance").is_some(), + water_breathing: self.get("water_breathing").is_some() || self.get("conduit_power").is_some(), + protection: Vec::new(), + } + } + /// Attribute modifiers of active effects: (attribute, id, amount, operation). + pub fn modifiers(&self) -> Vec<(&'static str, &'static str, f64, &'static str)> { + let mut out = Vec::new(); + for e in &self.list { + let level = f64::from(e.amplifier + 1); + let m = match e.id { + "speed" => Some(("minecraft:movement_speed", "minecraft:effect.speed", 0.2, "add_multiplied_total")), + "slowness" => Some(("minecraft:movement_speed", "minecraft:effect.slowness", -0.15, "add_multiplied_total")), + "haste" => Some(("minecraft:attack_speed", "minecraft:effect.haste", 0.1, "add_multiplied_total")), + "mining_fatigue" => Some(("minecraft:attack_speed", "minecraft:effect.mining_fatigue", -0.1, "add_multiplied_total")), + "strength" => Some(("minecraft:attack_damage", "minecraft:effect.strength", 3.0, "add_value")), + "weakness" => Some(("minecraft:attack_damage", "minecraft:effect.weakness", -4.0, "add_value")), + "jump_boost" => Some(("minecraft:safe_fall_distance", "minecraft:effect.jump_boost", 1.0, "add_value")), + "health_boost" => Some(("minecraft:max_health", "minecraft:effect.health_boost", 4.0, "add_value")), + "luck" => Some(("minecraft:luck", "minecraft:effect.luck", 1.0, "add_value")), + "unluck" => Some(("minecraft:luck", "minecraft:effect.unluck", -1.0, "add_value")), + _ => None, + }; + if let Some((a, id, amount, op)) = m { + out.push((a, id, amount * level, op)); + } + } + out + } + /// `Player.getDestroySpeed` effect factors (haste/conduit, mining fatigue). + pub fn mining_speed_factor(&self) -> f32 { + let mut f = 1.0; + let haste = self.amplifier("haste").max(self.amplifier("conduit_power")); + if let Some(a) = haste { + f *= 1.0 + (a + 1) as f32 * 0.2; + } + if let Some(a) = self.amplifier("mining_fatigue") { + f *= match a { + 0 => 0.3, + 1 => 0.09, + 2 => 0.0027, + _ => 8.1e-4, + }; + } + f + } +} +/// Effect and equipment facts the movement and damage kernels query. +#[derive(Clone, Debug, Default)] +pub struct StatusFlags { + pub jump_boost: Option, + pub slow_falling: bool, + pub levitation: Option, + pub resistance: Option, + pub fire_resistance: bool, + pub water_breathing: bool, + /// Armor enchantment protection per damage type id (`EnchantmentHelper.getDamageProtection`). + pub protection: Vec<(String, f32)>, +} +impl StatusFlags { + pub fn protection(&self, damage_type: &str) -> f32 { + self.protection.iter().find(|(t, _)| *t == damage_type).map_or(0.0, |(_, p)| *p) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn update_keeps_stronger_and_hides_longer() { + let mut fx = PlayerEffects::default(); + fx.add(EffectInstance::new("speed", 9600, 0)); + // A stronger but shorter effect takes over and hides the long one. + fx.add(EffectInstance::new("speed", 1800, 1)); + let e = fx.get("speed").unwrap(); + assert_eq!((e.amplifier, e.duration), (1, 1800)); + assert_eq!(e.hidden.as_ref().map(|h| (h.amplifier, h.duration)), Some((0, 9600))); + for _ in 0..1800 { + fx.tick(); + } + let e = fx.get("speed").unwrap(); + assert_eq!((e.amplifier, e.duration), (0, 7800)); + // Weaker and shorter: ignored. + assert!(!fx.add(EffectInstance::new("speed", 100, 0))); + } + + #[test] + fn regeneration_and_poison_intervals() { + let mut fx = PlayerEffects::default(); + fx.add(EffectInstance::new("regeneration", 900, 0)); + let heals = (0..900).flat_map(|_| fx.tick()).filter(|a| *a == EffectAction::Heal(1.0)).count(); + // Duration 900..1 divisible by 50: 18 heals. + assert_eq!(heals, 18); + assert!(fx.get("regeneration").is_none()); + let mut fx = PlayerEffects::default(); + fx.add(EffectInstance::new("poison", 432, 1)); + let hurts = (0..432).flat_map(|_| fx.tick()).filter(|a| matches!(a, EffectAction::Hurt(..))).count(); + // Interval 25 >> 1 = 12: 432/12 = 36 hits. + assert_eq!(hurts, 36); + } + + #[test] + fn potions_split_instant_and_lasting() { + let (lasting, now) = PlayerEffects::potion_effects(Some("minecraft:strong_healing"), 1.0); + assert!(lasting.is_empty()); + assert_eq!(now, vec![EffectAction::Heal(8.0)]); + let (lasting, _) = PlayerEffects::potion_effects(Some("minecraft:long_swiftness"), 0.25); + assert_eq!((lasting[0].id, lasting[0].duration), ("speed", 2400)); + let (lasting, _) = PlayerEffects::potion_effects(Some("minecraft:turtle_master"), 1.0); + assert_eq!(lasting.len(), 2); + let mut fx = PlayerEffects::default(); + fx.add(EffectInstance::new("haste", 100, 1)); + assert!((fx.mining_speed_factor() - 1.4).abs() < 1e-6); + assert_eq!(fx.modifiers().len(), 1); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f462aeaf2..23b38e6ed 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1,6 +1,8 @@ //! The playable game loop: streaming world, player simulation at 20 ticks/s, //! block interaction, inventory and HUD. mod control; +mod enchant_effects; +mod potions; mod station_control; mod stations; use horizon_client::{ @@ -316,6 +318,8 @@ struct Game<'a> { container: Option<(i32, i32, i32)>, /// Open workstation menu (enchanting table, anvil, ...). station: Option, + /// Status effects and thrown potions (game/potions.rs). + potions: potions::PotionState, scratch_slot: Option, mining: Option, destroy_delay: u32, @@ -891,7 +895,7 @@ impl Game<'_> { held.as_ref(), &mut self.world.random, ); - let silk = false; + let silk = held.as_ref().is_some_and(|h| h.enchantment_level("minecraft:silk_touch") > 0); for d in drops { if &*d.item != "minecraft:air" { self.pop_resource(pos, d); @@ -904,14 +908,15 @@ impl Game<'_> { } // Tools lose durability on blocks with nonzero hardness. if facts.hardness > 0.0 - && let Some(stack) = self.inventory[self.selected].as_mut() - && let Some(info) = self.res.items.get(&stack.item) - && info.max_damage > 0 - && !info.tool.is_empty() + && let Some(stack) = self.inventory[self.selected].clone() + && let Some(max) = self.res.items.get(&stack.item).filter(|i| i.max_damage > 0 && !i.tool.is_empty()).map(|i| i.max_damage) { - stack.damage += 1; - if stack.damage >= info.max_damage { - self.inventory[self.selected] = None; + let loss = self.durability_loss(&stack, 1); + if let Some(stack) = self.inventory[self.selected].as_mut() { + stack.damage += loss; + if stack.damage >= max { + self.inventory[self.selected] = None; + } } } } @@ -972,6 +977,9 @@ impl Game<'_> { } let Some(stack) = self.held().cloned() else { return Ok(()) }; let Some(info) = self.res.items.get(&stack.item).cloned() else { return Ok(()) }; + if self.use_potion_item(&stack)? { + return Ok(()); + } if &*stack.item == "minecraft:bow" { if self.using.is_none() { self.using = Some((self.selected, 0)); @@ -1060,6 +1068,9 @@ impl Game<'_> { self.using = None; return; }; + if self.tick_drinking(slot, ticks, &stack) { + return; + } if &*stack.item == "minecraft:bow" { self.using = Some((slot, ticks + 1)); return; @@ -1131,13 +1142,14 @@ impl Game<'_> { // Player.getDestroySpeed / BlockBehaviour.getDestroyProgress. let held = self.held(); let mut speed = self.res.items.mining_speed(held, &facts.name); + speed = self.modify_destroy_speed(speed); let player = self.player.as_ref().ok_or("no player")?; if !player.ground.on_ground { speed /= 5.0; } let eye = self.eye_position().unwrap_or_default(); if self.res.facts.get(self.world.block(eye[0].floor() as i32, eye[1].floor() as i32, eye[2].floor() as i32)).fluid == Fluid::Water { - speed /= 5.0; + speed *= self.submerged_mining_speed(); } let harvest = !facts.requires_tool || self.res.items.correct_for_drops(held, &facts.name); let progress = if facts.hardness == 0.0 { @@ -1378,6 +1390,8 @@ impl Game<'_> { self.screen = Screen::Dead; self.capture(false); } + self.tick_effects(); + self.tick_burning(); self.tick_using(); self.tick_mining()?; self.tick_items(); @@ -1597,6 +1611,7 @@ impl Game<'_> { self.draw_item(&mut batch, &stack, w / 2.0 - 90.0 + i as f32 * 20.0 + 2.0, h - 19.0); } } + self.draw_effect_icons(&mut batch); let atlas = &self.res.atlas; if !self.creative && let Some(p) = &self.player @@ -2451,7 +2466,7 @@ impl Game<'_> { } let held = self.held().cloned(); let modifiers = held.as_ref().and_then(|h| self.res.items.get(&h.item)).map(|i| (i.attack_damage, i.attack_speed)).unwrap_or((0.0, 0.0)); - let damage = 1.0 + modifiers.0; + let damage = 1.0 + modifiers.0 + self.effect_attack_bonus(); let speed = (4.0 + modifiers.1).max(0.1); let delay = 20.0 / speed; let scale = ((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0); @@ -2462,6 +2477,9 @@ impl Game<'_> { if crit { amount *= 1.5; } + // Enchantment damage (sharpness, smite, bane) scaled by the attack strength. + let target_kind = self.mobs[index].kind.id.clone(); + amount += self.enchant_damage_bonus(&format!("minecraft:{}", target_kind.trim_start_matches("minecraft:"))) * scale; self.attack_ticks = 0; if let Some(p) = self.player.as_mut() && !self.creative @@ -2482,13 +2500,16 @@ impl Game<'_> { let event = format!("minecraft:{}", kind.sounds[if dead { 2 } else { 1 }]); let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0; self.audio.play(&event, Some(center), 1.0, pitch); - if let Some(stack) = self.inventory[self.selected].as_mut() - && let Some(info) = self.res.items.get(&stack.item) - && info.max_damage > 0 + self.post_attack(index); + if let Some(stack) = self.inventory[self.selected].clone() + && let Some(max) = self.res.items.get(&stack.item).filter(|i| i.max_damage > 0).map(|i| i.max_damage) { - stack.damage += 1; - if stack.damage >= info.max_damage { - self.inventory[self.selected] = None; + let loss = self.durability_loss(&stack, 1); + if let Some(stack) = self.inventory[self.selected].as_mut() { + stack.damage += loss; + if stack.damage >= max { + self.inventory[self.selected] = None; + } } } } @@ -2682,6 +2703,7 @@ impl Game<'_> { let at = [player.position.x, player.position.y, player.position.z]; self.audio.play("minecraft:entity.player.hurt", Some(at), 1.0, 1.0); self.hurt_armor(amount); + self.thorns(from); } } MobEvent::Shoot(from, target) => { @@ -3277,12 +3299,14 @@ impl Game<'_> { } } } + self.apply_enchantment_attributes(); } /// Inventory.hurtArmor: each piece loses max(1, damage / 4) durability. fn hurt_armor(&mut self, damage: f32) { let amount = ((damage / 4.0) as u32).max(1); let mut broke = false; - for slot in &mut self.armor { + let losses: Vec = (0..4).map(|i| self.armor[i].clone().map_or(amount, |s| self.durability_loss(&s, amount))).collect(); + for (slot, amount) in self.armor.iter_mut().zip(losses) { if let Some(stack) = slot.as_mut() && let Some(info) = self.res.items.get(&stack.item) && info.max_damage > 0 @@ -3346,6 +3370,10 @@ impl Game<'_> { if self.creative { return; } + let amount = match self.inventory[self.selected].clone() { + 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 @@ -3544,6 +3572,9 @@ impl Game<'_> { }); } self.orbs = orbs; + if gained > 0 { + gained = self.mending(gained); + } if gained > 0 { let at = self.eye_position(); let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.35 + 0.9; @@ -3574,10 +3605,12 @@ impl Game<'_> { let speed = f64::from(power) * 3.0; let v = [(dir[0] + jitter()) * speed, (dir[1] + jitter()) * speed, (dir[2] + jitter()) * speed]; let p = Vec3::new(eye[0], eye[1] - 0.1, eye[2]); - self.arrows.push(Arrow { from_player: true, critical: power >= 1.0, position: p, previous: p, velocity: Vec3::new(v[0], v[1], v[2]), stuck: false, age: 0, base_damage: 2.0 }); + let (power_bonus, infinity) = self.bow_enchantments(); + self.arrows.push(Arrow { from_player: true, critical: power >= 1.0, position: p, previous: p, velocity: Vec3::new(v[0], v[1], v[2]), stuck: false, age: 0, base_damage: 2.0 + power_bonus }); let pitch = 1.0 / (self.world.random.next_float() * 0.4 + 1.2) + power * 0.5; self.audio.play("minecraft:entity.arrow.shoot", Some(eye), 1.0, pitch); if !self.creative + && !infinity && let Some(i) = arrow_slot && let Some(s) = self.inventory[i].as_mut() { @@ -4780,6 +4813,7 @@ pub fn run() -> Result<()> { craft_size: 2, container: None, station: None, + potions: Default::default(), scratch_slot: None, mining: None, destroy_delay: 0, diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs new file mode 100644 index 000000000..a562c2953 --- /dev/null +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -0,0 +1,221 @@ +//! Enchantment effects on gameplay, read from the data-driven effect +//! components: efficiency and aqua affinity (`Player.getDestroySpeed`), +//! unbreaking (`minecraft:item_damage`), sharpness/smite/bane and power +//! (`minecraft:damage`), knockback, fire aspect, infinity (`minecraft:ammo_use`), +//! thorns (`minecraft:post_attack`), mending (`minecraft:repair_with_xp`) and +//! the armor attribute effects (respiration, depth strider, ...). +use super::Game; +use horizon_client::{enchant::EffectContext, items::ItemStack}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +impl Game<'_> { + /// `Player.getDestroySpeed` after the tool speed: mining efficiency, haste + /// and mining fatigue. + pub(super) fn modify_destroy_speed(&self, mut speed: f32) -> f32 { + if speed > 1.0 { + let held = self.inventory[self.selected].as_ref(); + speed += self.res.stations.enchantments.attribute_add(held, "minecraft:mining_efficiency") as f32; + } + speed * self.potions.effects.mining_speed_factor() + } + /// `Attributes.SUBMERGED_MINING_SPEED` (0.2, raised by aqua affinity). + pub(super) fn submerged_mining_speed(&self) -> f32 { + let mut total = 0.0; + for stack in self.armor.iter().flatten() { + for (attr, _, amount, op) in self.res.stations.enchantments.attributes(stack) { + if attr == "minecraft:submerged_mining_speed" && op == "add_multiplied_total" { + total += amount; + } + } + } + (0.2 * (1.0 + total)) as f32 + } + /// `EnchantmentHelper.processDurabilityChange` (unbreaking) for `amount` points. + pub(super) fn durability_loss(&mut self, stack: &ItemStack, amount: u32) -> u32 { + let e = &self.res.stations.enchantments; + if !e.has_component(stack, "minecraft:item_damage") { + return amount; + } + let ctx = EffectContext { tool: Some(&stack.item), items: Some(&self.res.items), ..Default::default() }; + e.modify_value(Some(stack), "minecraft:item_damage", &ctx, &mut self.world.random, amount as f32).max(0.0) as u32 + } + /// `getEnchantedDamage - base`: damage bonus of the held weapon against a mob type. + pub(super) fn enchant_damage_bonus(&mut self, target: &str) -> f32 { + let Some(held) = self.inventory[self.selected].clone() else { return 0.0 }; + let ctx = EffectContext { this: Some(target), attacker: Some("minecraft:player"), direct_attacker: Some("minecraft:player"), is_direct: true, damage_type: Some("minecraft:player_attack"), items: Some(&self.res.items), ..Default::default() }; + self.res.stations.enchantments.modify_value(Some(&held), "minecraft:damage", &ctx, &mut self.world.random, 0.0) + } + /// Strength / weakness on the attack damage attribute. + pub(super) fn effect_attack_bonus(&self) -> f32 { + let fx = &self.potions.effects; + fx.amplifier("strength").map_or(0.0, |a| 3.0 * (a + 1) as f32) - fx.amplifier("weakness").map_or(0.0, |a| 4.0 * (a + 1) as f32) + } + /// After a successful melee hit: knockback enchantment and fire aspect. + pub(super) fn post_attack(&mut self, mob: usize) { + let Some(held) = self.inventory[self.selected].clone() else { return }; + let Some(m) = self.mobs.get(mob) else { return }; + let kind = m.kind.id.clone(); + let ctx = EffectContext { this: Some(&kind), attacker: Some("minecraft:player"), direct_attacker: Some("minecraft:player"), is_direct: true, items: Some(&self.res.items), ..Default::default() }; + let knockback = self.res.stations.enchantments.modify_value(Some(&held), "minecraft:knockback", &ctx, &mut self.world.random, 0.0); + if knockback > 0.0 { + // LivingEntity.knockback(strength * 0.5, sin(yRot), -cos(yRot)). + let strength = f64::from(knockback) * 0.5; + let (s, c) = (f64::from(self.yaw.to_radians().sin()), f64::from(self.yaw.to_radians().cos())); + let (dx, dz) = (s, -c); + let l = (dx * dx + dz * dz).sqrt().max(1e-5); + let m = &mut self.mobs[mob]; + let v = m.velocity; + m.velocity = Vec3::new(v.x / 2.0 - dx / l * strength, if m.on_ground { (v.y / 2.0 + strength).min(0.4) } else { v.y }, v.z / 2.0 - dz / l * strength); + } + // minecraft:post_attack ignite effects of the attacker's weapon (fire aspect). + let mut ignite = 0.0f32; + for (id, level) in held.enchantments() { + let Some(def) = self.res.stations.enchantments.get(id) else { continue }; + for effect in def.effects["minecraft:post_attack"].as_array().into_iter().flatten() { + if effect["enchanted"] == "attacker" && effect["affected"] == "victim" && effect["effect"]["type"] == "minecraft:ignite" { + let mut random = self.world.random.clone(); + let ok = effect.get("requirements").is_none_or(|r| self.res.stations.enchantments.condition(r, *level, &ctx, &mut random)); + self.world.random = random; + if ok { + ignite = ignite.max(horizon_client::enchant::level_value(&effect["effect"]["duration"], *level)); + } + } + } + } + if ignite > 0.0 { + // Entity.igniteForSeconds; mobs burn for 1 damage per second. + let id = self.mobs[mob].id; + self.potions.burning.retain(|(m, _)| *m != id); + self.potions.burning.push((id, (ignite * 20.0) as i32)); + } + } + /// Burning mobs (fire aspect): one damage every 20 ticks, flame particles. + pub(super) fn tick_burning(&mut self) { + let mut burning = std::mem::take(&mut self.potions.burning); + burning.retain_mut(|(id, ticks)| { + *ticks -= 1; + let Some(m) = self.mobs.iter_mut().find(|m| m.id == *id && m.alive()) else { return false }; + if *ticks % 20 == 0 { + let at = [m.position.x, m.position.y, m.position.z]; + if m.hurt(1.0, None, &mut self.world.random) { + self.last_hurt_by_player.insert(*id); + let _ = at; + } + } + *ticks > 0 + }); + self.potions.burning = burning; + } + /// Thorns on worn armor when a mob at `from` hits the player. + pub(super) fn thorns(&mut self, from: [f64; 3]) { + let attacker = self + .mobs + .iter() + .enumerate() + .filter(|(_, m)| m.alive()) + .min_by(|a, b| { + let d = |m: &horizon_client::mobs::Mob| (m.position.x - from[0]).powi(2) + (m.position.y - from[1]).powi(2) + (m.position.z - from[2]).powi(2); + d(a.1).total_cmp(&d(b.1)) + }) + .map(|(i, _)| i); + let Some(attacker) = attacker else { return }; + for slot in 0..4 { + let Some(stack) = self.armor[slot].clone() else { continue }; + let level = stack.enchantment_level("minecraft:thorns"); + if level == 0 { + continue; + } + let Some(def) = self.res.stations.enchantments.get("minecraft:thorns") else { continue }; + let effect = def.effects["minecraft:post_attack"][0].clone(); + let ctx = EffectContext { items: Some(&self.res.items), ..Default::default() }; + let mut random = self.world.random.clone(); + let ok = self.res.stations.enchantments.condition(&effect["requirements"], level, &ctx, &mut random); + self.world.random = random; + if !ok { + continue; + } + // DamageEntity(min 1, max 5) and ChangeItemDamage(2). + let damage = 1.0 + self.world.random.next_float() * 4.0; + let center = { + let m = &mut self.mobs[attacker]; + m.hurt(damage, None, &mut self.world.random); + [m.position.x, m.position.y, m.position.z] + }; + self.audio.play("minecraft:enchant.thorns.hit", Some(center), 1.0, 1.0); + if let Some(s) = self.armor[slot].as_mut() { + s.damage += 2; + if self.res.items.get(&s.item).is_some_and(|i| s.damage >= i.max_damage) { + self.armor[slot] = None; + } + } + } + } + /// `ExperienceOrb.repairPlayerItems`: returns the experience left over. + pub(super) fn mending(&mut self, amount: u32) -> u32 { + let mut amount = amount; + loop { + // EnchantmentHelper.getRandomItemWith(REPAIR_WITH_XP, damaged): held and armor. + let mut candidates: Vec<(bool, usize)> = Vec::new(); + if let Some(s) = &self.inventory[self.selected] + && s.damage > 0 + && s.enchantment_level("minecraft:mending") > 0 + { + candidates.push((false, self.selected)); + } + for (i, s) in self.armor.iter().enumerate() { + if let Some(s) = s + && s.damage > 0 + && s.enchantment_level("minecraft:mending") > 0 + { + candidates.push((true, i)); + } + } + if candidates.is_empty() { + return amount; + } + let (armor, i) = candidates[self.world.random.next_int_bound(candidates.len() as i32).unwrap_or(0) as usize]; + let stack = if armor { self.armor[i].clone() } else { self.inventory[i].clone() }; + let Some(stack) = stack else { return amount }; + let ctx = EffectContext { items: Some(&self.res.items), ..Default::default() }; + let to_repair_xp = self.res.stations.enchantments.modify_value(Some(&stack), "minecraft:repair_with_xp", &ctx, &mut self.world.random, amount as f32) as u32; + let repaired = to_repair_xp.min(stack.damage); + let slot = if armor { &mut self.armor[i] } else { &mut self.inventory[i] }; + if let Some(s) = slot.as_mut() { + s.damage -= repaired; + } + if repaired == 0 || to_repair_xp == 0 { + return 0; + } + let remaining = amount.saturating_sub(repaired * amount / to_repair_xp); + if remaining == 0 { + return 0; + } + amount = remaining; + } + } + /// Bow enchantments at release: (extra base damage, infinity keeps the arrow). + pub(super) fn bow_enchantments(&mut self) -> (f64, bool) { + let Some(bow) = self.inventory[self.selected].clone() else { return (0.0, false) }; + let e = &self.res.stations.enchantments; + let ctx = EffectContext { direct_attacker: Some("minecraft:arrow"), attacker: Some("minecraft:player"), items: Some(&self.res.items), ..Default::default() }; + let power = e.modify_value(Some(&bow), "minecraft:damage", &ctx, &mut self.world.random, 0.0); + let ammo_ctx = EffectContext { tool: Some("minecraft:arrow"), items: Some(&self.res.items), ..Default::default() }; + let infinity = e.has_component(&bow, "minecraft:ammo_use") && e.modify_value(Some(&bow), "minecraft:ammo_use", &ammo_ctx, &mut self.world.random, 1.0) == 0.0; + (f64::from(power), infinity) + } + /// Enchantment attribute modifiers of worn armor (respiration, depth strider...). + pub(super) fn apply_enchantment_attributes(&mut self) { + let mut wanted: Vec<(String, String, f64, String)> = Vec::new(); + for stack in self.armor.iter().flatten() { + wanted.extend(self.res.stations.enchantments.attributes(stack)); + } + let Some(p) = self.player.as_mut() else { return }; + for (attr, id, _, op) in std::mem::take(&mut self.potions.enchant_modifiers) { + let _ = p.set_modifier(&attr, &id, 0.0, &op, false); + } + for (attr, id, amount, op) in &wanted { + let _ = p.set_modifier(attr, id, *amount, op, true); + } + self.potions.enchant_modifiers = wanted; + } +} diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs new file mode 100644 index 000000000..d2ccb344c --- /dev/null +++ b/crates/horizon-client/src/game/potions.rs @@ -0,0 +1,345 @@ +//! Potions and status effects in the game: drinking (`PotionItem` via +//! `Consumable`), throwing splash/lingering potions (`ThrownSplashPotion`), +//! filling glass bottles (`BottleItem`), the per-tick effect application, +//! effect attribute modifiers and the HUD effect icons (`Hud.extractEffects`). +use super::{Game, Screen}; +use horizon_client::{ + brewing, + effects::{EffectAction, EffectInstance, PlayerEffects}, + hud::{HudBatch, rgba}, + items::ItemStack, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +/// A thrown splash or lingering potion in flight. +#[derive(Clone, Debug)] +pub(super) struct ThrownPotion { + stack: ItemStack, + position: Vec3, + velocity: Vec3, + age: u32, +} +/// Effects, thrown potions and the attribute modifiers last applied. +#[derive(Default)] +pub(super) struct PotionState { + pub(super) effects: PlayerEffects, + thrown: Vec, + applied: Vec<(&'static str, &'static str, f64, &'static str)>, + /// Armor the protection table was computed for. + protection_for: Option>>, + /// Mobs set on fire by fire aspect: (mob id, ticks left). + pub(super) burning: Vec<(u32, i32)>, + /// Enchantment attribute modifiers on the player: (attribute, id, amount, operation). + pub(super) enchant_modifiers: Vec<(String, String, f64, String)>, +} + +impl Game<'_> { + /// Right-click with a potion, splash/lingering potion or glass bottle. + pub(super) fn use_potion_item(&mut self, stack: &ItemStack) -> horizon_client::Result { + match &*stack.item { + "minecraft:potion" => { + if self.using.is_none() { + self.using = Some((self.selected, 0)); + } + Ok(true) + } + "minecraft:splash_potion" | "minecraft:lingering_potion" => { + let Some(eye) = self.eye_position() else { return Ok(true) }; + let pitch = 0.4 / (self.world.random.next_float() * 0.4 + 0.8); + let sound = if &*stack.item == "minecraft:splash_potion" { "minecraft:entity.splash_potion.throw" } else { "minecraft:entity.lingering_potion.throw" }; + self.audio.play(sound, Some(eye), 0.5, pitch); + // Projectile.shootFromRotation(xRot, yRot, -20, 0.5, 1.0). + let (yaw, pitch) = (self.yaw.to_radians(), (self.pitch - 20.0).to_radians()); + let dir = [-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos()]; + let r = &mut self.world.random; + let mut jitter = || f64::from(r.next_float() + r.next_float() - 1.0) * 0.0075; + let v = Vec3::new((f64::from(dir[0]) + jitter()) * 0.5, (f64::from(dir[1]) + jitter()) * 0.5, (f64::from(dir[2]) + jitter()) * 0.5); + let pv = self.player.as_ref().map_or(Vec3::ZERO, |p| p.velocity); + let on_ground = self.player.as_ref().is_some_and(|p| p.ground.on_ground); + let v = Vec3::new(v.x + pv.x, v.y + if on_ground { 0.0 } else { pv.y }, v.z + pv.z); + self.potions.thrown.push(ThrownPotion { stack: ItemStack { count: 1, ..stack.clone() }, position: Vec3::new(eye[0], eye[1] - 0.1, eye[2]), velocity: v, age: 0 }); + self.swing_arm(); + self.consume_held(); + Ok(true) + } + "minecraft:glass_bottle" => { + let Some(hit) = self.pick_fluid() else { return Ok(false) }; + let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + if self.res.facts.get(state).fluid != horizon_client::blocks::Fluid::Water { + return Ok(false); + } + let at = [f64::from(hit.pos[0]) + 0.5, f64::from(hit.pos[1]) + 0.5, f64::from(hit.pos[2]) + 0.5]; + self.audio.play("minecraft:item.bottle.fill", Some(at), 1.0, 1.0); + let water = ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"); + self.fill_held(water); + Ok(true) + } + _ => Ok(false), + } + } + /// `ItemUtils.createFilledResult`: replace one of the held stack. + fn fill_held(&mut self, filled: ItemStack) { + if self.creative { + let _ = self.give(filled); + return; + } + self.consume_held(); + if self.inventory[self.selected].is_none() { + self.inventory[self.selected] = Some(filled); + } else if let Some(rest) = self.give(filled) + && let Some(eye) = self.eye_position() + { + self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40); + } + } + /// Drinking a potion while right-click is held; true when handled. + pub(super) fn tick_drinking(&mut self, slot: usize, ticks: u32, stack: &ItemStack) -> bool { + if &*stack.item != "minecraft:potion" { + return false; + } + let ticks = ticks + 1; + let remaining = 32u32.saturating_sub(ticks); + let eye = self.eye_position().unwrap_or_default(); + // Consumable.emitParticlesAndSounds: the drink sound every 4 ticks near the end. + if remaining <= 25 && remaining % 4 == 0 { + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.audio.play("minecraft:entity.generic.drink", Some(eye), 0.5, pitch); + } + if ticks < 32 { + self.using = Some((slot, ticks)); + return true; + } + self.using = None; + let (lasting, now) = PlayerEffects::potion_effects(stack.potion(), 1.0); + for e in lasting { + self.potions.effects.add(e); + } + for a in now { + self.apply_effect_action(a); + } + if !self.creative { + if let Some(s) = self.inventory[slot].as_mut() { + s.count -= 1; + if s.count == 0 { + self.inventory[slot] = None; + } + } + let bottle = ItemStack::new("minecraft:glass_bottle", 1); + if self.inventory[slot].is_none() { + self.inventory[slot] = Some(bottle); + } else if let Some(rest) = self.give(bottle) { + self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40); + } + } + true + } + fn apply_effect_action(&mut self, action: EffectAction) { + let creative = self.creative; + let rules = self.world.health_rules; + let Some(p) = self.player.as_mut() else { return }; + match action { + EffectAction::Heal(amount) => { + let max = p.attribute("minecraft:max_health").unwrap_or(20.0) as f32; + let h = p.health.health(); + if h > 0.0 { + let _ = p.set_health((h + amount).min(max), false); + } + } + EffectAction::Hurt(source, amount) => { + if creative { + return; + } + if let Some(id) = self.motion.health.damage.id(source) { + let _ = p.hurt(&self.motion.health, rules, id, amount); + } + } + EffectAction::Exhaust(amount) => { + p.health.food.exhaustion = (p.health.food.exhaustion + amount).min(40.0); + } + EffectAction::Eat(nutrition, saturation) => { + let food = &mut p.health.food; + food.food = (food.food + nutrition).clamp(0, 20); + food.saturation = (food.saturation + nutrition as f32 * saturation * 2.0).clamp(0.0, food.food as f32); + } + } + } + /// `LivingEntity.tickEffects`, attribute modifiers and the status flags. + pub(super) fn tick_effects(&mut self) { + if self.player.as_ref().is_none_or(|p| p.health.dead_or_dying()) { + self.potions.effects.clear(); + } + for action in self.potions.effects.tick() { + self.apply_effect_action(action); + } + let modifiers = self.potions.effects.modifiers(); + if modifiers != self.potions.applied + && let Some(p) = self.player.as_mut() + { + for (attr, id, _, op) in &self.potions.applied { + let _ = p.set_modifier(attr, id, 0.0, op, false); + } + for (attr, id, amount, op) in &modifiers { + let _ = p.set_modifier(attr, id, *amount, op, true); + } + self.potions.applied = modifiers; + } + // EnchantmentHelper.getDamageProtection per damage type, recomputed on armor change. + let armor: Vec> = self.armor.to_vec(); + if self.potions.protection_for.as_ref() != Some(&armor) { + let mut table = Vec::new(); + let e = &self.res.stations.enchantments; + let mut random = horizon_core::random::LegacyRandom::new(0); + for (_, def) in self.motion.health.damage.entries() { + let ctx = horizon_client::enchant::EffectContext { items: Some(&self.res.items), damage_type: Some(&def.name), this: Some("minecraft:player"), ..Default::default() }; + let total: f32 = armor.iter().flatten().map(|s| e.modify_value(Some(s), "minecraft:damage_protection", &ctx, &mut random, 0.0)).sum(); + if total > 0.0 { + table.push((def.name.clone(), total)); + } + } + self.potions.protection_for = Some(armor); + if let Some(p) = self.player.as_mut() { + p.status.protection = table; + } + } + let mut status = self.potions.effects.status(); + if let Some(p) = self.player.as_mut() { + status.protection = std::mem::take(&mut p.status.protection); + p.status = status; + } + self.tick_thrown_potions(); + } + fn tick_thrown_potions(&mut self) { + let mut thrown = std::mem::take(&mut self.potions.thrown); + let mut landed = Vec::new(); + thrown.retain_mut(|t| { + t.age += 1; + let next = Vec3::new(t.position.x + t.velocity.x, t.position.y + t.velocity.y, t.position.z + t.velocity.z); + // Hit a block along the step (sampled), a mob, or fell out of the world. + let steps = 4; + let mut hit = None; + for i in 1..=steps { + let f = f64::from(i) / f64::from(steps); + let p = Vec3::new(t.position.x + t.velocity.x * f, t.position.y + t.velocity.y * f, t.position.z + t.velocity.z * f); + let state = self.world.block(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); + if self.res.facts.get(state).full_collision || self.mobs.iter().any(|m| m.alive() && (m.position.x - p.x).abs() < m.kind.width / 2.0 + 0.125 && (m.position.z - p.z).abs() < m.kind.width / 2.0 + 0.125 && p.y >= m.position.y && p.y <= m.position.y + m.kind.height) { + hit = Some(p); + break; + } + } + if let Some(p) = hit { + landed.push((t.stack.clone(), p)); + return false; + } + t.position = next; + // ThrowableItemProjectile: drag 0.99 then gravity 0.05. + t.velocity = Vec3::new(t.velocity.x * 0.99, t.velocity.y * 0.99 - 0.05, t.velocity.z * 0.99); + t.age < 1200 && t.position.y > -128.0 + }); + self.potions.thrown = thrown; + for (stack, at) in landed { + self.splash(&stack, at); + } + } + /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). + fn splash(&mut self, stack: &ItemStack, at: Vec3) { + let lingering = &*stack.item == "minecraft:lingering_potion"; + let event = if lingering { "minecraft:entity.lingering_potion.break" } else { "minecraft:entity.splash_potion.break" }; + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.audio.play(event, Some([at.x, at.y, at.z]), 1.0, pitch); + let color = brewing::potion_color(stack.potion()); + for _ in 0..8 { + let v = [f64::from(self.world.random.next_float() - 0.5) * 0.3, 0.2, f64::from(self.world.random.next_float() - 0.5) * 0.3]; + let p = horizon_client::particles::Particle::terrain(&mut self.world.random, [at.x, at.y, at.z], v, "item/splash_potion".into(), color); + self.particles.push(p); + } + let scale = if lingering { 0.25 } else { 1.0 }; + let Some(def) = stack.potion().and_then(brewing::potion) else { return }; + // The player. + if let Some(p) = self.player.as_ref() { + let center = Vec3::new(p.position.x, p.position.y + f64::from(p.dimensions.height) / 2.0, p.position.z); + let d2 = (center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2); + if d2 < 16.0 && (center.y - at.y).abs() <= 2.0 + f64::from(p.dimensions.height) { + let intensity = 1.0 - d2.sqrt() / 4.0; + for (id, duration, amp) in def.effects { + let instant = brewing::effect(id).is_some_and(|e| e.instant); + if instant { + if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) { + self.apply_effect_action(a); + } + } else { + let d = (intensity * f64::from(*duration) * f64::from(scale) + 0.5) as i32; + if d > 20 + && let Some(e) = brewing::effect(id) + { + self.potions.effects.add(EffectInstance::new(e.id, d, *amp)); + } + } + } + } + } + // Mobs take the instant effects (undead invert healing and harming). + let undead = &self.res.stations.enchantments.entity_tags; + let mut hits = Vec::new(); + for (i, m) in self.mobs.iter().enumerate() { + let d2 = (m.position.x - at.x).powi(2) + (m.position.y + m.kind.height / 2.0 - at.y).powi(2) + (m.position.z - at.z).powi(2); + if m.alive() && d2 < 16.0 { + let inverted = undead.get("minecraft:inverted_healing_and_harm").is_some_and(|t| t.contains(&m.kind.id)); + hits.push((i, 1.0 - d2.sqrt() / 4.0, inverted)); + } + } + for (i, intensity, inverted) in hits { + for (id, _, amp) in def.effects { + let harm = match *id { + "instant_damage" => !inverted, + "instant_health" => inverted, + _ => continue, + }; + let m = &mut self.mobs[i]; + if harm { + m.hurt((intensity * f64::from(6 << amp)) as i32 as f32, Some([at.x, at.y, at.z]), &mut self.world.random); + } else { + m.health = (m.health + (intensity * f64::from(4 << amp)) as i32 as f32).min(m.kind.max_health); + } + } + } + } + /// `Hud.extractEffects`: icons top-right, beneficial row then harmful row. + pub(super) fn draw_effect_icons(&self, batch: &mut HudBatch) { + if self.screen != Screen::Playing || self.potions.effects.list.is_empty() { + return; + } + let mut list: Vec<&EffectInstance> = self.potions.effects.list.iter().collect(); + let color = |e: &EffectInstance| brewing::effect(e.id).map_or(0, |d| d.color); + list.sort_by(|a, b| (a.ambient, a.duration == -1, a.duration, color(a)).cmp(&(b.ambient, b.duration == -1, b.duration, color(b))).reverse()); + let (mut good, mut bad) = (0, 0); + let atlas = &self.res.atlas; + for e in list { + let beneficial = brewing::effect(e.id).is_some_and(|d| d.category == brewing::Category::Beneficial); + let mut x = batch.width; + let mut y = 1.0; + if beneficial { + good += 1; + x -= 25.0 * good as f32; + } else { + bad += 1; + x -= 25.0 * bad as f32; + y += 26.0; + } + let mut alpha = 1.0f32; + if e.ambient { + batch.sprite(atlas, "gui/sprites/hud/effect_background_ambient", x, y); + } else { + batch.sprite(atlas, "gui/sprites/hud/effect_background", x, y); + if e.duration != -1 && e.duration <= 200 { + let d = e.duration as f32; + let used = 10.0 - (e.duration / 20) as f32; + alpha = ((d / 10.0 / 5.0 * 0.5).clamp(0.0, 0.5) + (d * std::f32::consts::PI / 5.0).cos() * (used / 10.0 * 0.25).clamp(0.0, 0.25)).clamp(0.0, 1.0); + } + } + batch.sprite_scaled(atlas, &format!("mob_effect/{}", e.id), x + 3.0, y + 3.0, 18.0, 18.0, rgba(255, 255, 255, (alpha * 255.0) as u8)); + } + } + pub(super) fn effects_json(&self) -> serde_json::Value { + serde_json::Value::Array(self.potions.effects.list.iter().map(|e| serde_json::json!({ "id": e.id, "duration": e.duration, "amplifier": e.amplifier })).collect()) + } +} diff --git a/crates/horizon-client/src/game/station_control.rs b/crates/horizon-client/src/game/station_control.rs index fdb8b7955..a7a71c2b4 100644 --- a/crates/horizon-client/src/game/station_control.rs +++ b/crates/horizon-client/src/game/station_control.rs @@ -14,6 +14,8 @@ pub(super) const HELP: &[&str] = &[ "enchant ID LEVEL enchant the held item (books store the enchantment)", "potion ITEM POTION give a potion item (potion, splash_potion, lingering_potion, tipped_arrow)", "menu JSON dump of the open menu, carried stack and inventory", + "effect ID SECONDS [AMPLIFIER] give a status effect (effect clear removes all)", + "effects list active status effects", "close close the open menu", ]; fn id(name: &str) -> String { @@ -138,6 +140,18 @@ impl Game<'_> { "slots": slots, }))) } + "effect" => { + if arg(1)? == "clear" { + self.potions.effects.clear(); + return ok(); + } + let def = horizon_client::brewing::effect(arg(1)?).ok_or("unknown effect")?; + let seconds: i32 = arg(2)?.parse()?; + let amp: i32 = words.get(3).map_or(Ok(0), |a| a.parse())?; + self.potions.effects.add(horizon_client::effects::EffectInstance::new(def.id, seconds * 20, amp)); + ok() + } + "effects" => Ok(Some(json!({ "effects": self.effects_json(), "health": self.player.as_ref().map(|p| p.health.health()) }))), "close" => { self.close_container(); self.screen = Screen::Playing; diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 49e6319ac..3b0169ab3 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -174,11 +174,7 @@ impl Game<'_> { pub(super) fn close_station(&mut self) { let Some(station) = self.station.take() else { return }; for stack in station.inputs.into_iter().flatten() { - if let Some(rest) = self.give(stack) - && let Some(eye) = self.eye_position() - { - self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40); - } + self.give_or_drop(stack); } } pub(super) fn station_slots(&self) -> Option> { diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index fedb8db09..e4bf7b96b 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -229,6 +229,7 @@ impl PlayerMotion { dead: &mut h.dead, sync_velocity: &mut h.sync_velocity, game_time: h.game_time, + status: self.status.clone(), }; Ok(ServerPlayerCombat::new( &mut self.attributes, @@ -264,6 +265,8 @@ pub(crate) struct Environment<'a> { pub(crate) dead: &'a mut bool, pub(crate) sync_velocity: &'a mut bool, pub(crate) game_time: i64, + /// Resistance, fire resistance and armor protection (effects.rs). + pub(crate) status: crate::effects::StatusFlags, } impl Environment<'_> { fn event(&mut self, event: HealthEvent) { @@ -310,10 +313,10 @@ impl ServerDamageEnvironment for Environment<'_> { Ok(()) } // empty equipment fn has_resistance(&mut self) -> io::Result { - Ok(false) + Ok(self.status.resistance.is_some()) } fn resistance_amplifier(&mut self) -> io::Result { - Err(io::Error::other("no resistance effect")) + self.status.resistance.ok_or_else(|| io::Error::other("no resistance effect")) } fn award_resisted(&mut self, value: i32) -> io::Result<()> { self.stat("resisted", value) @@ -325,8 +328,8 @@ impl ServerDamageEnvironment for Environment<'_> { Err(io::Error::other("no damage attacker")) } fn damage_protection(&mut self, _: ()) -> io::Result { - Ok(0.0) - } // empty equipment + Ok(self.status.protection(&self.source.definition().name)) + } fn award_self(&mut self, stat: DamageStat, value: i32) -> io::Result<()> { self.stat( match stat { @@ -426,7 +429,7 @@ impl HurtWorld for Environment<'_> { Ok(self.source.hurt_tag(tag)) } fn fire_resistance(&mut self, _: &mut State) -> io::Result { - Ok(false) + Ok(self.status.fire_resistance) } fn sleeping(&mut self, _: &mut State) -> io::Result { Ok(false) diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index fa6a0f20e..1182844d1 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -72,6 +72,7 @@ impl HudAtlas { walk(&textures.join("misc"), &mut files); walk(&textures.join("entity"), &mut files); walk(&textures.join("particle"), &mut files); + walk(&textures.join("mob_effect"), &mut files); files.retain(|p| { let s = p.to_string_lossy(); (!s.contains("title/background") || s.contains("panorama_")) && !s.contains("realms") && !s.contains("presets") diff --git a/crates/horizon-client/src/hunger.rs b/crates/horizon-client/src/hunger.rs index 1a70d975b..531bc12b6 100644 --- a/crates/horizon-client/src/hunger.rs +++ b/crates/horizon-client/src/hunger.rs @@ -134,6 +134,7 @@ impl FoodWorld for TickWorld<'_> { dead: self.dead, sync_velocity: self.sync_velocity, game_time: self.game_time, + status: Default::default(), }; 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 da184a553..10284d4c3 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -327,6 +327,10 @@ struct LootContext<'a> { killed_by_player: bool, } impl LootContext<'_> { + /// Level of an enchantment on the tool / killer's weapon. + fn enchantment_level(&self, id: &str) -> u32 { + self.held.map_or(0, |h| h.enchantment_level(id)) + } fn number(&self, v: &Value, random: &mut LegacyRandom) -> f32 { match v { Value::Number(n) => n.as_f64().unwrap_or(0.0) as f32, @@ -374,14 +378,17 @@ impl LootContext<'_> { }; match kind { "minecraft:survives_explosion" => true, - "minecraft:tool/can_silk_touch" => false, + "minecraft:tool/can_silk_touch" => self.enchantment_level("minecraft:silk_touch") > 0, "minecraft:tool/can_shear" => self.held.is_some_and(|h| &*h.item == "minecraft:shears"), "minecraft:inverted" => !self.condition(&c["term"], random), "minecraft:any_of" => c["terms"].as_array().into_iter().flatten().any(|t| self.condition(t, random)), "minecraft:all_of" => c["terms"].as_array().into_iter().flatten().all(|t| self.condition(t, random)), "minecraft:random_chance" => random.next_float() < self.number(&c["chance"], random), "minecraft:table_bonus" => { - let chance = c["chances"][0].as_f64().unwrap_or(0.0) as f32; + // BonusLevelTableCondition: chances[min(level, len - 1)]. + let level = self.enchantment_level(c["enchantment"].as_str().unwrap_or("")) as usize; + let chances = c["chances"].as_array().map_or(&[][..], Vec::as_slice); + let chance = chances.get(level.min(chances.len().saturating_sub(1))).and_then(Value::as_f64).unwrap_or(0.0) as f32; random.next_float() < chance } "minecraft:match_block" | "minecraft:block_state_property" => { @@ -405,17 +412,32 @@ impl LootContext<'_> { } "minecraft:match_tool" => { let items = &c["predicate"]["items"]; - match (self.held, items) { + let items_ok = match (self.held, items) { + (_, Value::Null) => self.held.is_some(), (Some(h), Value::String(s)) => match s.strip_prefix('#') { Some(tag) => self.items.item_tags.get(tag).is_some_and(|t| t.contains(&*h.item)), None => **s == *h.item, }, _ => false, - } + }; + // ItemPredicate "minecraft:enchantments": each entry needs a level in range. + let enchants_ok = c["predicate"]["predicates"]["minecraft:enchantments"].as_array().into_iter().flatten().all(|e| { + let level = self.enchantment_level(e["enchantments"].as_str().unwrap_or("")); + let min = e["levels"]["min"].as_u64().unwrap_or(1) as u32; + let max = e["levels"]["max"].as_u64().map_or(u32::MAX, |m| m as u32); + level >= min.max(1) && level <= max + }); + items_ok && enchants_ok } "minecraft:killed_by_player" => self.killed_by_player, "minecraft:random_chance_with_enchanted_bonus" => { - random.next_float() < c["unenchanted_chance"].as_f64().unwrap_or(0.0) as f32 + let level = if self.killed_by_player && self.block.is_empty() { self.enchantment_level(c["enchantment"].as_str().unwrap_or("")) } else { 0 }; + let chance = if level > 0 { + crate::enchant::level_value(&c["enchanted_chance"], level) + } else { + c["unenchanted_chance"].as_f64().unwrap_or(0.0) as f32 + }; + random.next_float() < chance } // Entity flags, equipment and damage-source predicates: none hold // for an unenchanted player kill without fire or lightning. @@ -526,6 +548,44 @@ impl LootContext<'_> { let base = if f["add"].as_bool() == Some(true) { stack.count as i32 } else { 0 }; stack.count = (base + n).max(0) as u32; } + "minecraft:apply_bonus" => { + let level = self.enchantment_level(f["enchantment"].as_str().unwrap_or("")) as i32; + let count = stack.count as i32; + let params = &f["parameters"]; + stack.count = match f["formula"].as_str().unwrap_or("") { + "minecraft:ore_drops" if level > 0 => { + let bonus = (random.next_int_bound(level + 2).unwrap_or(0) - 1).max(0); + count * (bonus + 1) + } + "minecraft:uniform_bonus_count" => { + let multiplier = params["bonusMultiplier"].as_i64().unwrap_or(1) as i32; + count + random.next_int_bound(multiplier * level + 1).unwrap_or(0) + } + "minecraft:binomial_with_bonus_count" => { + let (extra, p) = (params["extra"].as_i64().unwrap_or(0) as i32, params["probability"].as_f64().unwrap_or(0.0) as f32); + let mut n = count; + for _ in 0..level + extra { + if random.next_float() < p { + n += 1; + } + } + n + } + _ => count, + } + .max(0) as u32; + } + "minecraft:enchanted_count_increase" => { + // Attacker's level x count, rounded (looting). + let level = self.enchantment_level(f["enchantment"].as_str().unwrap_or("")); + if level > 0 && self.killed_by_player && self.block.is_empty() { + let add = level as f32 * self.number(&f["count"], random); + stack.count = (stack.count as i32 + add.round() as i32).max(0) as u32; + if let Some(limit) = f["limit"].as_i64().filter(|l| *l > 0) { + stack.count = stack.count.min(limit as u32); + } + } + } "minecraft:limit_count" => { let limit = &f["limit"]; if let Some(min) = limit["min"].as_i64() { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index ebd9b2da3..f2db3d27f 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -15,6 +15,7 @@ pub mod crafting; pub mod enchant; pub mod creative; pub mod collisions; +pub mod effects; pub mod entities; pub mod environment; pub mod gfx; diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index fb5a835b9..948dbf49d 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -152,6 +152,8 @@ pub struct PlayerMotion { pub attributes: LiveAttributes i32>>, pub impulse: ImpulseContext, pub health: crate::health::PlayerHealth, + /// Status effects and armor protection seen by movement and damage. + pub status: crate::effects::StatusFlags, } fn attribute_error(error: impl std::fmt::Debug) -> io::Error { io::Error::other(format!("movement attribute: {error:?}")) @@ -189,6 +191,7 @@ impl PlayerMotion { .map_err(attribute_error)?; Ok(Self { health: crate::health::PlayerHealth::new(&resources.health, &mut attributes)?, + status: crate::effects::StatusFlags::default(), impulse: ImpulseContext::default(), position, velocity: Vec3::ZERO, @@ -920,7 +923,7 @@ impl LivingAirWorld for MotionWorld<'_, '_, '_> { Ok(false) } fn levitation_amplifier(&mut self) -> Result> { - Ok(None) + Ok(self.player.status.levitation) } fn is_client_side(&mut self) -> Result { Ok(false) @@ -970,10 +973,10 @@ impl LivingMotionWorld for MotionWorld<'_, '_, '_> { )?) } fn has_jump_boost(&mut self) -> Result { - Ok(false) + Ok(self.player.status.jump_boost.is_some()) } fn jump_boost_amplifier(&mut self) -> Result { - Err("absent jump boost".into()) + self.player.status.jump_boost.ok_or_else(|| "absent jump boost".into()) } fn sprinting(&mut self) -> Result { Ok(self.player.sprinting) @@ -991,7 +994,7 @@ impl LivingMotionWorld for MotionWorld<'_, '_, '_> { self.player.attribute("minecraft:gravity") } fn has_slow_falling(&mut self) -> Result { - Ok(false) + Ok(self.player.status.slow_falling) } fn controlling_passenger_is_player(&mut self) -> Result { Ok(false)