diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 46e32f280..5c1955dce 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -254,26 +254,16 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.remove(&"home_pos".into()); } } + "minecraft:zombie_villager" => { + map.insert("VillagerData".into(), villager_data(m)); + map.insert("VillagerDataFinalized".into(), Tag::Byte(1)); + let xp = m.extra.trade.as_deref().map_or(0, |t| t.xp); + map.insert("Xp".into(), Tag::Int(xp)); + put_offers(map, m); + crate::mobs::zombie_villager::write_nbt(m, map); + } "minecraft:villager" => { - use crate::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; - let data = Tag::compound([ - ( - "type", - string(&format!( - "minecraft:{}", - VILLAGER_TYPES[m.extra.variant as usize % VILLAGER_TYPES.len()] - )), - ), - ( - "profession", - string(&format!( - "minecraft:{}", - PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()] - )), - ), - ("level", Tag::Int(i32::from(m.extra.variant3.max(1)))), - ]); - map.insert("VillagerData".into(), data); + map.insert("VillagerData".into(), villager_data(m)); let t = m.extra.trade.as_deref().cloned().unwrap_or_default(); map.insert("Xp".into(), Tag::Int(t.xp)); map.insert("LastRestock".into(), Tag::Long(t.last_restock)); @@ -568,6 +558,14 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - ) { read_villager(&mut m, tag); } + if m.species() == crate::mobs::Species::ZombieVillager { + read_villager(&mut m, tag); + let xp = number(tag.get("Xp")).unwrap_or(0) as i32; + if xp != 0 { + m.extra.trade.get_or_insert_with(Default::default).xp = xp; + } + crate::mobs::zombie_villager::read_nbt(&mut m, tag); + } if m.species() == crate::mobs::Species::Allay { if let Some(Tag::List(inv)) = tag.get("Inventory") && let Some(first) = inv.first() @@ -1016,6 +1014,27 @@ pub fn boat_from_nbt(tag: &Tag) -> Option<(Vec3, Vec3, f32)> { Some((position(tag)?, motion(tag), rotation(tag)[0])) } +/// `VillagerData`: type, profession and level. +fn villager_data(m: &Mob) -> Tag { + use crate::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; + Tag::compound([ + ( + "type", + string(&format!( + "minecraft:{}", + VILLAGER_TYPES[m.extra.variant as usize % VILLAGER_TYPES.len()] + )), + ), + ( + "profession", + string(&format!( + "minecraft:{}", + PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()] + )), + ), + ("level", Tag::Int(i32::from(m.extra.variant3.max(1)))), + ]) +} /// `AbstractVillager` "Offers" (`MerchantOffers.CODEC`). fn put_offers(map: &mut Compound, m: &Mob) { let Some(t) = &m.extra.trade else { return }; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b8f4a8529..99ae58669 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -65,6 +65,7 @@ mod trading; mod trident; mod villagers; mod wither; +mod zombie_villagers; use horizon_client::{ Result, assets::Assets, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 59145f16c..328913510 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -871,10 +871,12 @@ impl Game<'_> { amount, source, } => { + let mut killed = false; if let Some(t) = self.mobs.iter_mut().find(|m| m.id == target) { let hit = t.damage(amount, source); if hit { let (kind, center, dead) = (t.kind.clone(), t.center(), !t.alive()); + killed = dead; let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 @@ -890,6 +892,9 @@ impl Game<'_> { } } } + if killed && let Some(Who::Mob(killer)) = source.attacker { + self.zombie_killed(killer, target); + } } MobEvent::FinishAdmiring { mob } => self.finish_admiring(mob), MobEvent::Hiss { mob } => { @@ -1037,6 +1042,7 @@ impl Game<'_> { MobEvent::CreakingTearDown { center, spread } => { self.creaking_tear_down(center, spread) } + MobEvent::CureZombieVillager { mob } => self.cure_zombie_villager(mob), MobEvent::VillagerMeet { mob, other } => self.villager_meet(mob, other), MobEvent::VillagerBirth { parent, partner } => self.villager_birth(parent, partner), MobEvent::GolemCheck { mob, needed } => self.villager_golem_check(mob, needed), @@ -1773,6 +1779,9 @@ impl Game<'_> { .unwrap_or_default(); let creative = self.creative; let selected = self.selected; + if self.interact_zombie_villager(index, &item) { + return Ok(true); + } if self.interact_trader(index, &item)? { self.swing_arm(); return Ok(true); diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 00ed63cee..7a3c5908f 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -19,6 +19,23 @@ pub(super) struct ThrownPotion { velocity: Vec3, age: u32, } +/// A mob's effect ids carry the `minecraft:` namespace. +fn mob_effect_id(id: &str) -> Option<&'static str> { + use std::{collections::HashMap, sync::OnceLock}; + static IDS: OnceLock> = OnceLock::new(); + let id = id.trim_start_matches("minecraft:"); + IDS.get_or_init(|| { + brewing::EFFECTS + .iter() + .map(|e| { + let full: &'static str = Box::leak(format!("minecraft:{}", e.id).into_boxed_str()); + (e.id, full) + }) + .collect() + }) + .get(id) + .copied() +} impl Game<'_> { /// A splash potion, lingering potion or experience bottle in flight (the /// player's throws and dispensers both end up here). @@ -489,11 +506,21 @@ impl Game<'_> { } } for (i, intensity, inverted) in hits { - for (id, _, amp) in def.effects { + for (id, duration, amp) in def.effects { let harm = match *id { "instant_damage" => !inverted, "instant_health" => inverted, - _ => continue, + _ => { + // `Potion.applySplash`: timed effects last in + // proportion to how close the mob was. + let d = (intensity * f64::from(*duration) * scale + 0.5) as i32; + if d > 20 + && let Some(name) = mob_effect_id(id) + { + self.mobs[i].add_effect(name, d, *amp); + } + continue; + } }; let m = &mut self.mobs[i]; if harm { diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index 6dea14edb..027380482 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -99,29 +99,9 @@ impl Game<'_> { }; self.res.stations.trades.offers_from_set(&ctx, set, random) } - /// `Villager.mobInteract` / `WanderingTrader.mobInteract`: shake the - /// head without offers, else open the trading screen. - pub(super) fn interact_trader( - &mut self, - index: usize, - item: &str, - ) -> horizon_client::Result { - let m = &self.mobs[index]; - let species = m.species(); - if !matches!(species, Species::Villager | Species::WanderingTrader) - || !m.alive() - || item == "minecraft:villager_spawn_egg" - || self.station.is_some() - { - return Ok(false); - } - if m.is_baby() { - let mut events = Vec::new(); - villager::set_unhappy(&mut self.mobs[index], &mut events); - self.handle_mob_events(events)?; - return Ok(true); - } - // AbstractVillager.getOffers: generated on first use. + /// `AbstractVillager.getOffers`: generated on first use. + pub(super) fn ensure_offers(&mut self, index: usize) { + let species = self.mobs[index].species(); if self.mobs[index].extra.trade.is_none() { let m = &self.mobs[index]; let variant = VILLAGER_TYPES[m.extra.variant as usize % VILLAGER_TYPES.len()]; @@ -147,6 +127,30 @@ impl Game<'_> { ..Default::default() })); } + } + /// `Villager.mobInteract` / `WanderingTrader.mobInteract`: shake the + /// head without offers, else open the trading screen. + pub(super) fn interact_trader( + &mut self, + index: usize, + item: &str, + ) -> horizon_client::Result { + let m = &self.mobs[index]; + let species = m.species(); + if !matches!(species, Species::Villager | Species::WanderingTrader) + || !m.alive() + || item == "minecraft:villager_spawn_egg" + || self.station.is_some() + { + return Ok(false); + } + if m.is_baby() { + let mut events = Vec::new(); + villager::set_unhappy(&mut self.mobs[index], &mut events); + self.handle_mob_events(events)?; + return Ok(true); + } + self.ensure_offers(index); let m = &self.mobs[index]; let mut trade = m.extra.trade.as_deref().cloned().unwrap_or_default(); // Villager.updateSpecialPrices: reputation and Hero of the Village. diff --git a/crates/horizon-client/src/game/zombie_villagers.rs b/crates/horizon-client/src/game/zombie_villagers.rs new file mode 100644 index 000000000..c68c0f1c1 --- /dev/null +++ b/crates/horizon-client/src/game/zombie_villagers.rs @@ -0,0 +1,254 @@ +//! Zombie villagers in the world: zombies turning the villagers they kill +//! into zombie villagers (`Zombie.killedEntity`), the golden apple that starts +//! a cure (`ZombieVillager.mobInteract`), and the cured villager that +//! remembers who saved it (`ZombieVillager.finishConversion`). +use super::Game; +use horizon_client::{ + advancements as adv, + gossip::GossipType, + mobs::{Mob, Species, villager, zombie_villager}, +}; +use horizon_core::random::RandomSource; +use horizon_world::food::Difficulty; + +/// The `Zombie` subclasses that convert the villagers they kill. +fn is_zombie(s: Species) -> bool { + matches!( + s, + Species::Zombie + | Species::Husk + | Species::Drowned + | Species::ZombieVillager + | Species::ZombifiedPiglin + ) +} +/// Whether a zombie turns the villager it killed: always on Hard, half the +/// time on Normal (`Zombie.killedEntity`). +fn infects(difficulty: Difficulty, coin: impl FnOnce() -> bool) -> bool { + match difficulty { + Difficulty::Hard => true, + Difficulty::Normal => !coin(), + _ => false, + } +} + +impl Game<'_> { + /// `Zombie.killedEntity`: a villager killed by a zombie may rise as a + /// zombie villager keeping its profession, trades and gossip. + pub(super) fn zombie_killed(&mut self, killer: u32, victim: u32) { + let Some(k) = self.mobs.iter().position(|m| m.id == killer) else { + return; + }; + let Some(v) = self.mobs.iter().position(|m| m.id == victim) else { + return; + }; + if !is_zombie(self.mobs[k].species()) + || self.mobs[v].species() != Species::Villager + || self.mobs[v].alive() + || self.mobs[v].removed + { + return; + } + let difficulty = self.world.health_rules.difficulty; + let random = &mut self.mobs[k].random; + if !infects(difficulty, || random.next_boolean()) { + return; + } + // The villager is gone without dying: no drops, no death animation. + let old = self.mobs[v].clone(); + self.mobs[v].removed = true; + self.mobs[v].health = 0.0; + let at = [old.position.x, old.position.y, old.position.z]; + let Some(id) = self.spawn_mob("minecraft:zombie_villager", at, old.persistent) else { + return; + }; + let ensure = self.mobs.iter().position(|m| m.id == victim); + if let Some(i) = ensure { + self.ensure_offers(i); + } + let old = ensure.map_or(old, |i| self.mobs[i].clone()); + let Some(z) = self.mobs.iter_mut().find(|m| m.id == id) else { + return; + }; + convert_to_zombie_villager(&old, z); + let killer_at = self.mobs[k].position; + let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0; + self.audio.play( + "minecraft:entity.zombie.infect", + Some([killer_at.x, killer_at.y, killer_at.z]), + 2.0, + pitch, + ); + } + + /// `ZombieVillager.mobInteract`: a golden apple on a weakened zombie + /// villager starts the cure and is eaten; without weakness it does + /// nothing. Returns whether the click was used. + pub(super) fn interact_zombie_villager(&mut self, index: usize, item: &str) -> bool { + let m = &self.mobs[index]; + if m.species() != Species::ZombieVillager || item != "minecraft:golden_apple" { + return false; + } + if !m.has_effect("minecraft:weakness") { + return true; + } + self.consume_held(); + let starter = self.level.player_uuid; + let time = zombie_villager::WAIT_MIN + + self + .world + .random + .next_int_bound(zombie_villager::WAIT_SPREAD) + .unwrap_or(0); + let mut events = Vec::new(); + zombie_villager::start_converting(&mut self.mobs[index], starter, time, &mut events); + let _ = self.handle_mob_events(events); + self.swing_arm(); + true + } + + /// `ZombieVillager.finishConversion`: the villager returns with its + /// data, trades, experience and gossip, and the curing player earns the + /// village's trust. + pub(super) fn cure_zombie_villager(&mut self, id: u32) { + let Some(i) = self.mobs.iter().position(|m| m.id == id) else { + return; + }; + if self.mobs[i].removed || zombie_villager::cure(&self.mobs[i]).is_none() { + return; + } + let old = self.mobs[i].clone(); + self.mobs[i].removed = true; + let at = [old.position.x, old.position.y, old.position.z]; + let Some(vid) = self.spawn_mob("minecraft:villager", at, old.persistent) else { + return; + }; + let Some(v) = self.mobs.iter_mut().find(|m| m.id == vid) else { + return; + }; + convert_to_villager(&old, v); + // `Villager.onReputationEventFrom(ZOMBIE_VILLAGER_CURED)`. + let starter = zombie_villager::cure(&old).and_then(|c| c.starter); + let player = self.level.player_uuid; + let cured_by_player = starter.is_some() && starter == player; + if cured_by_player && let Some(uuid) = starter { + let g = &mut villager::ext_mut(v).gossips; + g.add(uuid, GossipType::MajorPositive, 20); + g.add(uuid, GossipType::MinorPositive, 25); + } + let cured = v.clone(); + let villager_view = self.mob_entity(&cured); + let zombie_view = self.mob_entity(&old); + if cured_by_player { + self.trigger_cured_zombie_villager(&zombie_view, &villager_view); + } + let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0; + self.audio.play( + "minecraft:entity.zombie_villager.converted", + Some(at), + 2.0, + pitch, + ); + } + + /// `CuredZombieVillagerTrigger`. + fn trigger_cured_zombie_villager( + &mut self, + zombie: &adv::EntityView, + villager: &adv::EntityView, + ) { + let me = self.player_entity(); + let (zombie, villager) = (zombie.clone(), villager.clone()); + self.trigger("minecraft:cured_zombie_villager", move |c, w| { + let origin = me.position; + let ctx = |e| adv::Entities { + this: Some(e), + origin, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &ctx(&me), w) + && adv::conditions(&c["zombie"], &ctx(&zombie), w) + && adv::conditions(&c["villager"], &ctx(&villager), w) + }); + } +} + +/// `Mob.convertTo` (`ConversionType.SINGLE`, keeping equipment and the +/// pick-up-loot flag): what any converted mob carries over. +fn carry_over(from: &Mob, to: &mut Mob) { + to.position = from.position; + to.previous = from.position; + to.velocity = from.velocity; + to.yaw = from.yaw; + to.previous_yaw = from.yaw; + to.body_yaw = from.body_yaw; + to.previous_body_yaw = from.body_yaw; + to.head_yaw = from.head_yaw; + to.previous_head_yaw = from.head_yaw; + to.head_pitch = from.head_pitch; + to.previous_head_pitch = from.head_pitch; + to.fall_distance = from.fall_distance; + to.hurt_time = from.hurt_time; + to.on_ground = from.on_ground; + to.fire_ticks = from.fire_ticks; + to.persistent = from.persistent; + to.custom_name = from.custom_name.clone(); + to.name_visible = from.name_visible; + to.extra.pick_up_loot = from.extra.pick_up_loot; + to.extra.main_hand = from.extra.main_hand.clone(); + to.extra.off_hand = from.extra.off_hand.clone(); + to.extra.head = from.extra.head.clone(); + to.extra.chest = from.extra.chest.clone(); + to.extra.legs = from.extra.legs.clone(); + to.extra.feet = from.extra.feet.clone(); + to.extra.effects = from.extra.effects.clone(); + // VillagerData and the trades, experience and gossip. + to.extra.variant = from.extra.variant; + to.extra.variant2 = from.extra.variant2; + to.extra.variant3 = from.extra.variant3.max(1); + to.extra.trade = from.extra.trade.clone(); + if let Some(g) = villager::ext(from).map(|e| e.gossips.clone()) { + villager::ext_mut(to).gossips = g; + } +} +/// A villager rises as a zombie villager (never as an adult-age baby: a baby +/// stays a baby for good). +pub(super) fn convert_to_zombie_villager(from: &Mob, to: &mut Mob) { + carry_over(from, to); + to.extra.age = if from.is_baby() { i32::MIN / 2 } else { 0 }; +} +/// A cured zombie villager becomes a villager again, queasy for 10 seconds. +pub(super) fn convert_to_villager(from: &Mob, to: &mut Mob) { + carry_over(from, to); + to.extra.age = if from.is_baby() { -24000 } else { 0 }; + to.add_effect("minecraft:nausea", 200, 0); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn zombies_convert_by_difficulty() { + assert!(infects(Difficulty::Hard, || unreachable!())); + assert!(!infects(Difficulty::Easy, || false)); + assert!(!infects(Difficulty::Peaceful, || false)); + // Normal: a coin toss that spares the villager when it is true. + assert!(infects(Difficulty::Normal, || false)); + assert!(!infects(Difficulty::Normal, || true)); + } + #[test] + fn every_zombie_kind_infects() { + for s in [ + Species::Zombie, + Species::Husk, + Species::Drowned, + Species::ZombieVillager, + Species::ZombifiedPiglin, + ] { + assert!(is_zombie(s)); + } + assert!(!is_zombie(Species::Skeleton) && !is_zombie(Species::Villager)); + } +} diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 9261846a1..fab8e0101 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -42,6 +42,7 @@ pub mod villager; pub mod witch; pub mod wither; mod world; +pub mod zombie_villager; use crate::{blocks::BlockFacts, mesher::Vertex, world::World}; pub use data::MobData; @@ -708,6 +709,10 @@ pub enum MobEvent { table: &'static str, at: [f64; 3], }, + /// A zombie villager's cure is complete: the game turns it back into a villager. + CureZombieVillager { + mob: u32, + }, /// A creaking bound to the heart at `home` was hurt (`creakingHurt` when a player did it). CreakingHurt { home: [i32; 3], diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 45957180f..21b545070 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -605,7 +605,7 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { let Some(p) = &w.player else { return true }; let d = m.distance_sqr(p.position); // Patrols and raiders (`removeWhenFarAway`, `requiresCustomPersistence`). - if super::raider::keeps_alive(m, d) { + if super::raider::keeps_alive(m, d) || super::zombie_villager::keeps_alive(m) { return true; } let despawn = if m.kind.category == "water_ambient" { diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index d640b6973..01a8e1af2 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -504,11 +504,7 @@ pub fn layers(m: &Mob) -> Vec { } else { "entity/zombie_villager" }; - let baby = if m.is_baby() && m.species() == S::Villager { - "baby/" - } else { - "" - }; + let baby = if m.is_baby() { "baby/" } else { "" }; push( &mut v, &model, @@ -525,9 +521,10 @@ pub fn layers(m: &Mob) -> Vec { white, false, ); - if m.species() == S::Villager && prof != "nitwit" { + if prof != "nitwit" { + // `LEVEL_LOCATIONS` clamps the level to 1..=5. let level = ["stone", "iron", "gold", "emerald", "diamond"] - [(m.extra.variant3 as usize).min(4)]; + [(m.extra.variant3.max(1) as usize - 1).min(4)]; push( &mut v, &model, @@ -612,7 +609,12 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 { m.previous.y + (m.position.y - m.previous.y) * a, m.previous.z + (m.position.z - m.previous.z) * a, ) - camera; - let body = m.previous_body_yaw + wrap(m.body_yaw - m.previous_body_yaw) * alpha; + let mut body = m.previous_body_yaw + wrap(m.body_yaw - m.previous_body_yaw) * alpha; + if shaking(m) { + // LivingEntityRenderer.setupRotations: a rapid wobble. + let ticks = (m.age as f32 + alpha).floor(); + body += (f64::from(ticks * 3.25).cos() * std::f64::consts::PI * 0.4) as f32; + } let sleep = (m.species() == Species::Villager) .then(|| super::villager::sleep_pose(m)) .flatten(); @@ -644,6 +646,18 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 { base *= species_scale(m, alpha); base * glam::Mat4::from_translation(glam::Vec3::new(0.0, -1.501, 0.0)) } +/// `LivingEntityRenderer.isShaking`: converting zombies, piglins and +/// hoglins, and a zombie villager being cured. +fn shaking(m: &Mob) -> bool { + match m.species() { + Species::ZombieVillager => super::zombie_villager::is_converting(m), + Species::Zombie | Species::Husk => m.extra.counter2 > 0, + Species::Piglin | Species::PiglinBrute | Species::Hoglin => { + !m.extra.flag2 && m.extra.counter2 > 0 + } + _ => false, + } +} fn flip_degrees(m: &Mob) -> f32 { match m.species() { Species::Spider | Species::CaveSpider | Species::Silverfish | Species::Endermite => 180.0, diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index ca7c9e0f5..c661b1c23 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -199,6 +199,9 @@ fn zombified_piglin_step(m: &mut Mob, cx: &mut Cx) { } } pub fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { + if m.species() == Species::ZombieVillager { + super::zombie_villager::step(m, cx); + } if m.species() == Species::ZombifiedPiglin { return zombified_piglin_step(m, cx); } diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index 82e7645bd..5f7c47c66 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -647,6 +647,8 @@ pub struct Ext { pub golem_until: i64, /// The `last_hurt_by_time` of the player's hit already counted. pub hurt_seen: i32, + /// A zombie villager's cure under way. + pub cure: Option, } pub fn ext(m: &Mob) -> Option<&Ext> { m.extra.villager.as_deref() diff --git a/crates/horizon-client/src/mobs/zombie_villager.rs b/crates/horizon-client/src/mobs/zombie_villager.rs new file mode 100644 index 000000000..51fb33c6d --- /dev/null +++ b/crates/horizon-client/src/mobs/zombie_villager.rs @@ -0,0 +1,164 @@ +//! Zombie villagers (`ZombieVillager`): the cure started by a golden apple on +//! a weakened one, the conversion clock that iron bars and beds speed up, and +//! the saved fields. Turning villagers into zombie villagers and back is done +//! by the game (`game/zombie_villagers.rs`), which owns entity creation. +use super::{Mob, MobEvent, MobWorld, Species, goals::Cx, villager}; +use horizon_core::random::RandomSource; +use horizon_world::nbt::{Compound, Tag}; + +/// `VILLAGER_CONVERSION_WAIT_MIN` and the width of the random range. +pub const WAIT_MIN: i32 = 3600; +pub const WAIT_SPREAD: i32 = 2401; +/// `MAX_SPECIAL_BLOCKS_COUNT` and `SPECIAL_BLOCK_RADIUS`. +const MAX_SPECIAL_BLOCKS: i32 = 14; +const RADIUS: i32 = 4; +const SPEEDS_UP_CURING: &str = "minecraft:speeds_up_zombie_villager_curing"; + +/// A cure under way: ticks left and the player who started it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Cure { + pub time: i32, + pub starter: Option<[i32; 4]>, +} + +pub fn cure(m: &Mob) -> Option<&Cure> { + villager::ext(m).and_then(|e| e.cure.as_ref()) +} +pub fn is_converting(m: &Mob) -> bool { + m.species() == Species::ZombieVillager && cure(m).is_some() +} +/// `removeWhenFarAway`: curing ones and those with experience stay. +pub fn keeps_alive(m: &Mob) -> bool { + m.species() == Species::ZombieVillager + && (is_converting(m) || m.extra.trade.as_ref().is_some_and(|t| t.xp != 0)) +} + +/// `ZombieVillager.startConverting`: weakness gives way to strength for the +/// length of the cure and the cure sound plays (entity event 16). +pub fn start_converting( + m: &mut Mob, + starter: Option<[i32; 4]>, + time: i32, + events: &mut Vec, +) { + villager::ext_mut(m).cure = Some(Cure { time, starter }); + m.extra.effects.retain(|e| e.0 != "minecraft:weakness"); + // Strength amplifier: min(difficulty id - 1, 0), always 0 with monsters. + m.add_effect("minecraft:strength", time, 0); + let pitch = m.random.next_float() * 0.7 + 0.3; + let volume = 1.0 + m.random.next_float(); + events.push(MobEvent::Sound( + "entity.zombie_villager.cure", + [m.position.x, m.eye_y(), m.position.z], + volume, + pitch, + )); +} + +/// `getConversionProgress`: 1 per tick, plus a chance per nearby iron bars or +/// bed (up to 14 of them) found on one tick in a hundred. +fn progress(m: &mut Mob, w: &MobWorld) -> i32 { + let mut amount = 1; + if m.random.next_float() < 0.01 { + let mut special = 0; + // `(int) getX()` truncates toward zero. + let (bx, by, bz) = ( + m.position.x as i32, + m.position.y as i32, + m.position.z as i32, + ); + 'scan: for x in bx - RADIUS..bx + RADIUS { + for y in by - RADIUS..by + RADIUS { + for z in bz - RADIUS..bz + RADIUS { + if special >= MAX_SPECIAL_BLOCKS { + break 'scan; + } + if w.has_tag(SPEEDS_UP_CURING, w.block_name(x, y, z)) { + if m.random.next_float() < 0.3 { + amount += 1; + } + special += 1; + } + } + } + } + } + amount +} + +/// `ZombieVillager.tick`: count the cure down, finishing it at zero. +pub fn step(m: &mut Mob, cx: &mut Cx) { + if !m.alive() || !is_converting(m) { + return; + } + let amount = progress(m, cx.w); + let Some(c) = villager::ext_mut(m).cure.as_mut() else { + return; + }; + c.time -= amount; + if c.time <= 0 { + cx.events.push(MobEvent::CureZombieVillager { mob: m.id }); + } +} + +/// `ConversionTime` (-1: not converting) and `ConversionPlayer`. +fn put_cure(map: &mut Compound, cure: Option) { + map.insert( + "ConversionTime".into(), + Tag::Int(cure.map_or(-1, |c| c.time)), + ); + if let Some(starter) = cure.and_then(|c| c.starter) { + map.insert("ConversionPlayer".into(), Tag::IntArray(starter.to_vec())); + } +} +fn parse_cure(tag: &Tag) -> Option { + let time = match tag.get("ConversionTime") { + Some(Tag::Int(v)) => *v, + _ => -1, + }; + (time != -1).then(|| Cure { + time, + starter: crate::save::uuid_from_tag(tag.get("ConversionPlayer")), + }) +} +/// The saved fields: the cure and the gossip. +pub fn write_nbt(m: &Mob, map: &mut Compound) { + put_cure(map, cure(m).copied()); + if let Some(e) = villager::ext(m) + && !e.gossips.is_empty() + { + map.insert("Gossips".into(), e.gossips.to_nbt()); + } +} +pub fn read_nbt(m: &mut Mob, tag: &Tag) { + let cure = parse_cure(tag); + let e = villager::ext_mut(m); + e.cure = cure; + e.gossips = tag + .get("Gossips") + .map(crate::gossip::Gossips::from_nbt) + .unwrap_or_default(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_cure_round_trips_through_nbt() { + let cure = Cure { + time: 4200, + starter: Some([1, 2, 3, 4]), + }; + let mut map = Compound::new(); + put_cure(&mut map, Some(cure)); + assert_eq!(parse_cure(&Tag::Compound(map)), Some(cure)); + } + #[test] + fn no_cure_saves_minus_one() { + let mut map = Compound::new(); + put_cure(&mut map, None); + assert_eq!(map.get(&"ConversionTime".into()), Some(&Tag::Int(-1))); + assert_eq!(parse_cure(&Tag::Compound(map)), None); + } +}