From af791c55b777cb838ab4959d46b0fb6396b315e2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:34:06 +0200 Subject: [PATCH] Add pillager patrols and the ominous banner Every ten minutes or so, in daylight and a fifth of the time, a patrol of pillagers spawns 24 to 48 blocks from a player who is not near a village, once the world is five days old and outside mushroom fields. The leader wears the ominous banner and heads for a distant target in ten block hops with its companions following; patrols hold their ground, shout to nearby raiders and attack together once something comes close. Natural spawns lead a patrol one time in seventeen. A fallen banner always drops, and a captain pillager drops an ominous bottle that gives Bad Omen when drunk. Patrol state, the banner's patterns and the bottle's amplifier are saved as vanilla NBT. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/entity_nbt.rs | 19 +- crates/horizon-client/src/game.rs | 3 + crates/horizon-client/src/game/creatures.rs | 40 +- crates/horizon-client/src/game/potions.rs | 9 +- crates/horizon-client/src/game/raids.rs | 205 +++++++++ crates/horizon-client/src/item_data.rs | 71 +++ crates/horizon-client/src/mobs.rs | 16 + crates/horizon-client/src/mobs/ai.rs | 5 + crates/horizon-client/src/mobs/raider.rs | 459 ++++++++++++++++++++ 9 files changed, 823 insertions(+), 4 deletions(-) create mode 100644 crates/horizon-client/src/game/raids.rs create mode 100644 crates/horizon-client/src/mobs/raider.rs diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index bd45054ac..4dcc75671 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -371,6 +371,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } _ => {} } + crate::mobs::raider::write_nbt(m, map); // LivingEntity equipment: what the mob holds now. if !crate::mobs::equine::is_equine(m.species()) { let mut equipment = match map.get(&"equipment".into()) { @@ -391,7 +392,22 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { equipment.get(&slot.into()).and_then(|e| e.get("id")), Some(Tag::String(s)) if s.to_string_lossy() == **id ); - if !keep { + if slot == "head" + && &**id == crate::mobs::raider::BANNER + && crate::mobs::raider::is_raider(m.species()) + { + // The captain's ominous banner keeps its patterns. + let has_patterns = equipment + .get(&slot.into()) + .and_then(|e| e.get("components")) + .is_some(); + if !has_patterns { + equipment.insert( + slot.into(), + crate::save::item_to_nbt(&crate::mobs::raider::ominous_banner()), + ); + } + } else if !keep { equipment.insert( slot.into(), Tag::compound([ @@ -616,6 +632,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.health = health; m.extra.flag2 = flag(tag, "wasOnGround"); } + crate::mobs::raider::read_nbt(&mut m, tag); // A mob saved mid-death finishes dying; one saved dead is dropped. if m.health <= 0.0 && m.death_time == 0 { return None; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6b705f8f1..5865d0adb 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -45,6 +45,7 @@ mod perspective; mod piglins; mod postprocess; mod potions; +mod raids; mod remote; mod render_control; mod render_tick; @@ -531,6 +532,7 @@ struct Game<'a> { mobs: Vec, arrows: Vec, creatures: creatures::Creatures, + raiding: raids::Raiding, attack_ticks: u32, last_hurt_by_player: HashSet, chest_open: HashMap<(i32, i32, i32), (f32, f32)>, @@ -7617,6 +7619,7 @@ pub fn run() -> Result<()> { mobs: Vec::new(), arrows: Vec::new(), creatures: Default::default(), + raiding: Default::default(), attack_ticks: 100, last_hurt_by_player: HashSet::new(), chest_open: HashMap::new(), diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 7f13adffc..b7f6c0699 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -115,6 +115,7 @@ fn seen(m: &Mob) -> Seen { bed: (m.species() == Species::Villager) .then_some(m.extra.bed) .flatten(), + active_raid: horizon_client::mobs::raider::has_active_raid(m), } } impl Game<'_> { @@ -191,6 +192,17 @@ impl Game<'_> { } /// Create a mob of `kind` at a position, finalized like a natural spawn. pub(super) fn spawn_mob(&mut self, kind: &str, at: [f64; 3], persistent: bool) -> Option { + self.spawn_mob_for(kind, at, persistent, false) + } + /// `spawn_mob` for a patrol or raid (`EntitySpawnReason.PATROL` / `EVENT`), + /// which never rolls a patrol leader. + pub(super) fn spawn_mob_for( + &mut self, + kind: &str, + at: [f64; 3], + persistent: bool, + scripted: bool, + ) -> Option { let kind = if kind.contains(':') { kind.to_owned() } else { @@ -208,6 +220,14 @@ impl Game<'_> { ); let difficulty = self.local_difficulty(at); spawning::finalize(&mut mob, &facts, &difficulty); + if !scripted { + let reason = if persistent { + horizon_client::mobs::raider::Reason::Other + } else { + horizon_client::mobs::raider::Reason::Natural + }; + horizon_client::mobs::raider::finalize(&mut mob, reason); + } let id = mob.id; self.mobs.push(mob); Some(id) @@ -265,7 +285,7 @@ impl Game<'_> { serde_json::json!({ "count": self.mobs.len(), "near": list, "projectiles": self.creatures.projectiles.len() }) } /// Highest motion-blocking (no leaves) block + 1 (Heightmap MOTION_BLOCKING_NO_LEAVES). - fn motion_top(&self, x: i32, z: i32) -> i32 { + pub(super) fn motion_top(&self, x: i32, z: i32) -> i32 { let top = if self.dim == Dim::Nether { 127 } else { 319 }; for y in (horizon_client::chunk::MIN_Y..=top).rev() { let f = self.res.facts.get(self.world.block(x, y, z)); @@ -602,6 +622,7 @@ impl Game<'_> { } self.tick_inhabited(); self.spawn_natural(); + self.tick_patrol_spawner(); let snapshot: Vec = self.mobs.iter().map(seen).collect(); let mut events = Vec::new(); let mut mobs = std::mem::take(&mut self.mobs); @@ -688,6 +709,7 @@ impl Game<'_> { for item in gear { self.spawn_item(ItemStack::new(item, 1), pos, [0.0, 0.2, 0.0], 10); } + self.raider_death_loot(m, pos); let worn = if horizon_client::mobs::equine::is_equine(m.species()) { [None, None, None, None] } else { @@ -703,6 +725,7 @@ impl Game<'_> { // Vexes never drop their sword. if let Some(item) = &item && by_player + && &**item != horizon_client::mobs::raider::BANNER && m.species() != Species::Vex && self.world.random.next_float() < 0.085 { @@ -978,6 +1001,21 @@ impl Game<'_> { MobEvent::CreakingTearDown { center, spread } => { self.creaking_tear_down(center, spread) } + MobEvent::PatrolTarget { mob, target } => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + horizon_client::mobs::raider::set_patrol_target(m, target); + } + } + MobEvent::RaiderTarget { + mob, + target, + aggressive, + } => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + m.ai.target = Some(target); + m.ai.aggressive |= aggressive; + } + } MobEvent::GiftLoot { table, at } => { let drops = self.res diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 53f9afe02..00ed63cee 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -52,7 +52,7 @@ 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" => { + "minecraft:potion" | "minecraft:ominous_bottle" => { if self.using.is_none() { self.using = Some((self.selected, 0)); } @@ -152,7 +152,8 @@ impl Game<'_> { } /// 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" { + let ominous = &*stack.item == "minecraft:ominous_bottle"; + if &*stack.item != "minecraft:potion" && !ominous { return false; } let ticks = ticks + 1; @@ -169,6 +170,10 @@ impl Game<'_> { return true; } self.using = None; + if ominous { + self.drink_ominous_bottle(slot, stack); + return true; + } let (lasting, now) = PlayerEffects::potion_effects(stack.potion(), 1.0); for e in lasting { self.potions.effects.add(e); diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs new file mode 100644 index 000000000..ab3e28827 --- /dev/null +++ b/crates/horizon-client/src/game/raids.rs @@ -0,0 +1,205 @@ +//! Pillager patrols (`PatrolSpawner`) and the village sections they avoid. +use super::{Dim, Game}; +use horizon_client::mobs::{Species, data, raider}; +use horizon_core::random::RandomSource; +use std::collections::HashSet; + +/// Patrol and raid state owned by the game. +#[derive(Default)] +pub(super) struct Raiding { + /// `PatrolSpawner.nextTick`. + patrol_next_tick: i32, +} + +/// `SectionPos` of a block position. +pub(super) fn section(p: [i32; 3]) -> (i32, i32, i32) { + (p[0] >> 4, p[1] >> 4, p[2] >> 4) +} +/// `PoiManager.DistanceTracker`: sections from the nearest village centre, +/// 7 when farther than 6. +pub(super) fn sections_to_village(centers: &HashSet<(i32, i32, i32)>, at: (i32, i32, i32)) -> i32 { + centers + .iter() + .map(|c| { + (c.0 - at.0) + .abs() + .max((c.1 - at.1).abs()) + .max((c.2 - at.2).abs()) + }) + .min() + .map_or(7, |d| d.min(7)) +} + +impl Game<'_> { + /// Sections holding a claimed village point of interest (a job site, + /// bed or bell a villager has taken): `PoiManager.isVillageCenter`. + pub(super) fn village_centers(&self) -> HashSet<(i32, i32, i32)> { + let mut out = HashSet::new(); + for m in &self.mobs { + if m.species() != Species::Villager || !m.alive() { + continue; + } + for p in [m.extra.home, m.extra.bed, m.extra.meeting] + .into_iter() + .flatten() + { + out.insert(section(p)); + } + } + out + } + /// `ServerLevel.isCloseToVillage`. + pub(super) fn close_to_village(&self, at: [i32; 3], distance: i32) -> bool { + distance <= 6 && sections_to_village(&self.village_centers(), section(at)) <= distance + } + /// `PatrolSpawner.tick`: every 10 minutes, a fifth of the time in + /// daylight, a patrol of pillagers spawns 24 to 48 blocks from a player + /// who is not near a village. + pub(super) fn tick_patrol_spawner(&mut self) { + if self.dim != Dim::Overworld + || self.world.health_rules.difficulty == horizon_world::food::Difficulty::Peaceful + || !self.ui.rules.bool("spawn_monsters") + || !self.ui.rules.bool("spawn_patrols") + { + return; + } + self.raiding.patrol_next_tick -= 1; + if self.raiding.patrol_next_tick > 0 { + return; + } + let delay = self.world.random.next_int_bound(1200).unwrap_or(0); + self.raiding.patrol_next_tick += 12000 + delay; + let bright = self.sky_darken() < 4; + let r = &mut self.world.random; + if !bright || r.next_int_bound(5).unwrap_or(1) != 0 { + return; + } + // One player: `players.get(random.nextInt(1))`. + let _ = r.next_int_bound(1); + let Some(p) = self.player.as_ref().map(|p| p.position) else { + return; + }; + if self.spectator() { + return; + } + let block = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; + if self.close_to_village(block, 2) { + return; + } + let r = &mut self.world.random; + let x = (24 + r.next_int_bound(24).unwrap_or(0)) * if r.next_boolean() { -1 } else { 1 }; + let z = (24 + r.next_int_bound(24).unwrap_or(0)) * if r.next_boolean() { -1 } else { 1 }; + let mut at = [block[0] + x, block[1], block[2] + z]; + // hasChunksAt(±10). + for (dx, dz) in [(-10, -10), (10, -10), (-10, 10), (10, 10)] { + if !self + .world + .chunks + .contains_key(&((at[0] + dx) >> 4, (at[2] + dz) >> 4)) + { + return; + } + } + // The `can_pillager_patrol_spawn` attribute: the early game timeline + // (first five days) and the mushroom fields forbid it. + let biome = self.biome_facts(at[0], at[1], at[2]); + if self.world.day_time < 120_000 || biome.mushroom { + return; + } + let f = self.local_difficulty([f64::from(at[0]), f64::from(at[1]), f64::from(at[2])]); + let group = f.effective.ceil() as i32 + 1; + for i in 0..group { + at[1] = self.motion_top(at[0], at[2]); + if !self.spawn_patrol_member(at, i == 0) && i == 0 { + break; + } + let r = &mut self.world.random; + at[0] += r.next_int_bound(5).unwrap_or(0) - r.next_int_bound(5).unwrap_or(0); + at[2] += r.next_int_bound(5).unwrap_or(0) - r.next_int_bound(5).unwrap_or(0); + } + } + /// A raider's ominous banner (drop chance 2.0: always dropped) and a + /// patrol captain's ominous bottle (`entities/pillager`). + pub(super) fn raider_death_loot(&mut self, m: &horizon_client::mobs::Mob, pos: [f64; 3]) { + if !raider::is_raider(m.species()) { + return; + } + if m.extra.head.as_deref() == Some(raider::BANNER) { + self.spawn_item(raider::ominous_banner(), pos, [0.0, 0.2, 0.0], 10); + } + if m.species() == Species::Pillager && raider::is_captain(m) { + let amplifier = self.world.random.next_int_bound(5).unwrap_or(0) as u8; + let amplifier = (amplifier > 0).then_some(amplifier); + let mut bottle = horizon_client::items::ItemStack::new("minecraft:ominous_bottle", 1); + bottle.data_mut().ominous_amplifier = amplifier; + self.spawn_item(bottle, pos, [0.0, 0.2, 0.0], 10); + } + } + /// `OminousBottleAmplifier.onConsume`: Bad Omen for 100 minutes at the + /// bottle's amplifier, then the dispose sound; the bottle is used up. + pub(super) fn drink_ominous_bottle( + &mut self, + slot: usize, + stack: &horizon_client::items::ItemStack, + ) { + let amplifier = stack.data().and_then(|d| d.ominous_amplifier).unwrap_or(0); + let mut effect = + horizon_client::effects::EffectInstance::new("bad_omen", 120_000, i32::from(amplifier)); + effect.visible = false; + self.potions.effects.add(effect); + let eye = self.eye_position().unwrap_or_default(); + self.audio + .play("minecraft:item.ominous_bottle.dispose", Some(eye), 1.0, 1.0); + if !self.creative + && let Some(s) = self.inventory[slot].as_mut() + { + s.count -= 1; + if s.count == 0 { + self.inventory[slot] = None; + } + } + } + /// `PatrolSpawner.spawnPatrolMember`: a pillager on a valid empty block + /// that may spawn there; the leader picks a target and wears the banner. + fn spawn_patrol_member(&mut self, at: [i32; 3], leader: bool) -> bool { + let state = self.world.block(at[0], at[1], at[2]); + let below = self.world.block(at[0], at[1] - 1, at[2]); + let empty = self.res.mob_data.state(state).flags & data::VALID_EMPTY_SPAWN != 0; + let valid = self.res.mob_data.state(below).flags & data::VALID_SPAWN != 0; + // PatrollingMonster.checkPatrollingMonsterSpawnRules. + if !empty || !valid || self.world.light(at[0], at[1], at[2]) & 15 > 8 { + return false; + } + let pos = [f64::from(at[0]), f64::from(at[1]), f64::from(at[2])]; + let Some(id) = self.spawn_mob_for("minecraft:pillager", pos, false, true) else { + return false; + }; + let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else { + return false; + }; + if leader { + raider::set_patrol_leader(m, true); + // findPatrolTarget runs before the mob is placed, so the target + // is around the world origin. + raider::find_patrol_target_from(m, [0, 0, 0]); + } + raider::finalize(m, raider::Reason::Patrol); + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sections_to_village_is_a_chebyshev_distance_capped_at_seven() { + let mut centers = HashSet::new(); + assert_eq!(sections_to_village(¢ers, (0, 0, 0)), 7); + centers.insert(section([40, 64, 40])); + assert_eq!(sections_to_village(¢ers, (2, 4, 2)), 0); + assert_eq!(sections_to_village(¢ers, (4, 4, 2)), 2); + assert_eq!(sections_to_village(¢ers, (-10, 4, 2)), 7); + assert_eq!(section([-1, -17, 15]), (-1, -2, 0)); + } +} diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index d7643d3dd..feb98fa38 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -35,7 +35,23 @@ pub struct StackData { pub writable_pages: Vec, /// `minecraft:written_book_content`. pub written: Option, + /// The raid captain's banner: `minecraft:banner_patterns` with the + /// ominous layers, its item name, rarity and hidden tooltip. + pub ominous_banner: bool, + /// `minecraft:ominous_bottle_amplifier` (None: the item's default, 0). + pub ominous_amplifier: Option, } +/// `Raid.getBannerComponentPatch`: the ominous banner's pattern layers. +pub const OMINOUS_LAYERS: [(&str, &str); 8] = [ + ("rhombus", "cyan"), + ("stripe_bottom", "light_gray"), + ("stripe_center", "gray"), + ("border", "light_gray"), + ("stripe_middle", "black"), + ("half_horizontal", "light_gray"), + ("circle", "light_gray"), + ("border", "black"), +]; /// `WrittenBookContent` with the pages as plain text. #[derive(Clone, Debug, Default, PartialEq)] pub struct WrittenBook { @@ -330,6 +346,39 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { Tag::List(d.charged.iter().map(crate::save::item_to_nbt).collect()), )); } + if d.ominous_banner { + let layer = |pattern: &str, color: &str| { + Tag::compound([ + ( + "pattern", + Tag::String(format!("minecraft:{pattern}").as_str().into()), + ), + ("color", Tag::String(color.into())), + ]) + }; + entries.push(( + "minecraft:banner_patterns", + Tag::List(OMINOUS_LAYERS.iter().map(|(p, c)| layer(p, c)).collect()), + )); + entries.push(( + "minecraft:tooltip_display", + Tag::compound([( + "hidden_components", + Tag::List(vec![Tag::String("minecraft:banner_patterns".into())]), + )]), + )); + entries.push(( + "minecraft:item_name", + Tag::compound([( + "translate", + Tag::String("block.minecraft.ominous_banner".into()), + )]), + )); + entries.push(("minecraft:rarity", Tag::String("uncommon".into()))); + } + if let Some(a) = d.ominous_amplifier { + entries.push(("minecraft:ominous_bottle_amplifier", Tag::Int(i32::from(a)))); + } if !d.container.is_empty() { let slots = d .container @@ -435,6 +484,15 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option Vec::new(), }, + ominous_banner: matches!( + c.get("minecraft:banner_patterns"), + Some(Tag::List(layers)) if layers.first().is_some_and(|l| + l.get("pattern").and_then(string).as_deref() == Some("minecraft:rhombus")) + ), + ominous_amplifier: c + .get("minecraft:ominous_bottle_amplifier") + .and_then(int) + .map(|v| v.clamp(0, 4) as u8), trim: c.get("minecraft:trim").and_then(|t| { Some(( Arc::from(t.get("material").and_then(string)?.as_str()), @@ -499,6 +557,19 @@ mod tests { assert_eq!(back.custom_name(), Some("Blade")); } + #[test] + fn ominous_items_round_trip() { + let mut banner = ItemStack::new("minecraft:white_banner", 1); + banner.data_mut().ominous_banner = true; + let tag = encode_components(&banner).unwrap(); + assert!(tag.get("minecraft:banner_patterns").is_some()); + let (_, back) = decode_components(Some(&tag)); + assert!(back.unwrap().ominous_banner); + let mut bottle = ItemStack::new("minecraft:ominous_bottle", 1); + bottle.data_mut().ominous_amplifier = Some(3); + let (_, back) = decode_components(encode_components(&bottle).as_ref()); + assert_eq!(back.unwrap().ominous_amplifier, Some(3)); + } #[test] fn plain_stacks_have_no_components() { let stack = ItemStack::new("minecraft:stone", 64); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index f53eb3901..d90acb0b1 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -29,6 +29,7 @@ pub mod nether; pub mod path; pub mod phantom; pub mod piglin; +pub mod raider; pub mod ravager; pub mod render; pub mod shulker; @@ -476,6 +477,8 @@ pub struct Extra { pub meeting: Option<[i32; 3]>, /// Villager and wandering trader offers and experience. pub trade: Option>, + /// A raider's patrol and raid state. + pub raider: Option>, } #[derive(Clone, Debug)] pub struct Mob { @@ -660,6 +663,17 @@ pub enum MobEvent { kind: DamageKind, amount: f32, }, + /// A patrol leader hands its patrol target to a companion. + PatrolTarget { + mob: u32, + target: [i32; 3], + }, + /// A raider is told to attack (`HoldGroundAttackGoal` shouting). + RaiderTarget { + mob: u32, + target: Who, + aggressive: bool, + }, /// Drop the loot of a gift table (chicken eggs, armadillo scutes). GiftLoot { table: &'static str, @@ -715,6 +729,8 @@ pub struct Seen { /// A villager's claimed job site and bed. pub job: Option<[i32; 3]>, pub bed: Option<[i32; 3]>, + /// A raider in an active raid. + pub active_raid: bool, } /// The player as mobs see it. #[derive(Clone, Debug)] diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index a0ae29a97..45957180f 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -173,6 +173,7 @@ pub fn register(m: &mut Mob) { Family::Villager => super::villager::register(m), Family::Creaking => super::creaking::register(m), } + super::raider::register(m); } /// Mob.tick additions that run before the entity tick (creeper fuse, puffing). fn pre_tick(m: &mut Mob, events: &mut Vec) { @@ -603,6 +604,10 @@ 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) { + return true; + } let despawn = if m.kind.category == "water_ambient" { 64.0 } else { diff --git a/crates/horizon-client/src/mobs/raider.rs b/crates/horizon-client/src/mobs/raider.rs new file mode 100644 index 000000000..95a8f9dea --- /dev/null +++ b/crates/horizon-client/src/mobs/raider.rs @@ -0,0 +1,459 @@ +//! Raiders (`PatrollingMonster` and `Raider`): the patrol state every +//! pillager, vindicator, evoker, witch and ravager carries, the long +//! distance patrol and hold-ground goals, the ominous banner a patrol leader +//! wears, and the saved fields. +use super::{ + Mob, MobEvent, MobWorld, Species, Who, + goals::{Cx, Goal, LOOK, MOVE, goal_clone}, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_world::nbt::Tag; + +/// The ominous banner is a white banner with the raid patterns; raiders wear +/// it as their head item. +pub const BANNER: &str = "minecraft:white_banner"; + +/// `PatrollingMonster` and `Raider` state (saved as `patrol_target`, +/// `PatrolLeader`, `Patrolling`, `Wave`, `CanJoinRaid`, `RaidId`). +#[derive(Clone, Debug, Default)] +pub struct State { + pub patrol_leader: bool, + pub patrolling: bool, + pub patrol_target: Option<[i32; 3]>, + /// Goal cooldown after a failed long distance path (game time). + pub patrol_cooldown_until: i64, + pub wave: i32, + pub can_join_raid: bool, + /// The raid this raider belongs to. + pub raid_id: Option, + pub ticks_outside_raid: i32, + pub celebrating: bool, + /// The raid is active (`hasActiveRaid`); set by the game every tick. + pub active_raid: bool, +} + +/// The raider species (`EntityTypeTags.RAIDERS`). +pub fn is_raider(s: Species) -> bool { + matches!( + s, + Species::Pillager + | Species::Vindicator + | Species::Evoker + | Species::Witch + | Species::Ravager + ) +} +/// `canBeLeader`: witches and ravagers never lead. +pub fn can_be_leader(s: Species) -> bool { + is_raider(s) && !matches!(s, Species::Witch | Species::Ravager) +} +pub fn state(m: &Mob) -> Option<&State> { + m.extra.raider.as_deref() +} +pub fn state_mut(m: &mut Mob) -> &mut State { + m.extra.raider.get_or_insert_with(Box::default) +} +pub fn has_active_raid(m: &Mob) -> bool { + state(m).is_some_and(|s| s.active_raid) +} +/// `Raider.isCaptain`: the banner on the head of a patrol leader. +pub fn is_captain(m: &Mob) -> bool { + m.extra.head.as_deref() == Some(BANNER) && state(m).is_some_and(|s| s.patrol_leader) +} + +pub fn register(m: &mut Mob) { + if !is_raider(m.species()) { + return; + } + m.extra.raider = Some(Box::default()); + let species = m.species(); + m.ai.goals.add(4, LongDistancePatrol::new(0.7, 0.595)); + // The illagers hold their ground in a patrol (Witch and Ravager do not). + if matches!(species, Species::Pillager | Species::Vindicator) { + m.ai.goals.add( + if species == Species::Pillager { 2 } else { 4 }, + HoldGroundAttack::new(10.0), + ); + } +} + +/// `Raid.getOminousBannerInstance`. +pub fn ominous_banner() -> crate::items::ItemStack { + let mut stack = crate::items::ItemStack::new(BANNER, 1); + stack.data_mut().ominous_banner = true; + stack +} + +/// `PatrollingMonster.setPatrolLeader`. +pub fn set_patrol_leader(m: &mut Mob, leader: bool) { + let s = state_mut(m); + s.patrol_leader = leader; + s.patrolling = true; +} +/// `PatrollingMonster.setPatrolTarget`. +pub fn set_patrol_target(m: &mut Mob, target: [i32; 3]) { + let s = state_mut(m); + s.patrol_target = Some(target); + s.patrolling = true; +} +/// `PatrollingMonster.findPatrolTarget`: somewhere within 500 blocks. +pub fn find_patrol_target(m: &mut Mob) { + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + find_patrol_target_from(m, at); +} +/// `findPatrolTarget` from a given block position. +pub fn find_patrol_target_from(m: &mut Mob, [x, y, z]: [i32; 3]) { + let dx = -500 + m.random.next_int_bound(1000).unwrap_or(0); + let dz = -500 + m.random.next_int_bound(1000).unwrap_or(0); + let s = state_mut(m); + s.patrol_target = Some([x + dx, y, z + dz]); + s.patrolling = true; +} +/// The leader's ominous banner and its drop chance of 2.0 (always dropped). +pub fn wear_banner(m: &mut Mob) { + m.extra.head = Some(BANNER.into()); +} +/// Why a mob was spawned (`EntitySpawnReason`), as far as raiders care. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reason { + /// Natural spawning: one leader in 17, and witches stay out of raids. + Natural, + /// Commands, eggs and other spawns: one leader in 17. + Other, + Patrol, + Event, +} +/// `PatrollingMonster.finalizeSpawn` and `Raider.finalizeSpawn`: a spawn +/// other than a patrol, raid or structure leads one time in 17, a patrol +/// leader wears the ominous banner, and every raider but a naturally spawned +/// witch can join a raid. +pub fn finalize(m: &mut Mob, reason: Reason) { + if !is_raider(m.species()) { + return; + } + let roll = matches!(reason, Reason::Natural | Reason::Other); + if roll && m.random.next_float() < 0.06 && can_be_leader(m.species()) { + state_mut(m).patrol_leader = true; + } + if state_mut(m).patrol_leader { + wear_banner(m); + } + let witch = m.species() == Species::Witch; + let s = state_mut(m); + if reason == Reason::Patrol { + s.patrolling = true; + } + s.can_join_raid = !witch || reason != Reason::Natural; +} + +/// `PatrollingMonster.removeWhenFarAway`: patrollers and raiders in a raid +/// are only despawned beyond 128 blocks (never inside a raid). +pub fn keeps_alive(m: &Mob, distance_squared: f64) -> bool { + match state(m) { + Some(s) => s.raid_id.is_some() || s.patrolling && distance_squared <= 16384.0, + None => false, + } +} + +/// `Heightmap.Types.MOTION_BLOCKING_NO_LEAVES` position above (x, z). +pub fn heightmap_pos(w: &MobWorld, x: i32, z: i32) -> [i32; 3] { + let top = crate::chunk::MIN_Y + crate::chunk::HEIGHT; + let y = (crate::chunk::MIN_Y..top) + .rev() + .find(|&y| { + let f = w.facts.get(w.world.block(x, y, z)); + (f.full_collision || f.fluid != crate::blocks::Fluid::None) + && !f.name.ends_with("leaves") + }) + .map_or(crate::chunk::MIN_Y, |y| y + 1); + [x, y, z] +} + +/// `Vec3.yRot` (the angle is in radians, and the patrol goal passes 90). +fn y_rot(v: Vec3, angle: f32) -> Vec3 { + let (cos, sin) = (f64::from(angle.cos()), f64::from(angle.sin())); + Vec3::new(v.x * cos + v.z * sin, v.y, v.z * cos - v.x * sin) +} + +/// `PatrollingMonster.LongDistancePatrolGoal`: walk toward the patrol target +/// in 10 block hops (curving around it), the leader dragging its companions. +#[derive(Clone, Debug)] +pub struct LongDistancePatrol { + speed: f64, + leader_speed: f64, +} +impl LongDistancePatrol { + pub fn new(speed: f64, leader_speed: f64) -> Self { + Self { + speed, + leader_speed, + } + } +} +/// Patrol companions within 16 blocks that are not in a raid. +fn companions(m: &Mob, w: &MobWorld) -> Vec { + w.others + .iter() + .filter(|s| { + s.id != m.id + && s.alive + && is_raider(s.species) + && !s.active_raid + && (s.position.x - m.position.x).abs() <= 16.0 + f64::from(m.width()) + && (s.position.y - m.position.y).abs() <= 16.0 + f64::from(m.height()) + && (s.position.z - m.position.z).abs() <= 16.0 + f64::from(m.width()) + }) + .map(|s| s.id) + .collect() +} +impl Goal for LongDistancePatrol { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(s) = state(m) else { return false }; + cx.w.game_time >= s.patrol_cooldown_until + && s.patrolling + && m.ai.target.is_none() + && s.patrol_target.is_some() + && !s.has_rider() + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if !m.ai.nav.is_done() { + return; + } + let leader = state(m).is_some_and(|s| s.patrol_leader); + let friends = companions(m, cx.w); + let Some(target) = state(m).and_then(|s| s.patrol_target) else { + return; + }; + if state(m).is_some_and(|s| s.patrolling) && friends.is_empty() { + state_mut(m).patrolling = false; + } else if leader && close_to_center(target, m.position, 10.0) { + find_patrol_target(m); + } else { + let to = Vec3::new( + f64::from(target[0]) + 0.5, + f64::from(target[1]), + f64::from(target[2]) + 0.5, + ); + let own = m.position; + let distance = own.subtract(to); + let to = y_rot(distance, 90.0).scale(0.4).add_vector(to); + let hop = to.subtract(own).normalize().scale(10.0).add_vector(own); + let at = heightmap_pos(cx.w, hop.x.floor() as i32, hop.z.floor() as i32); + let speed = if leader { + self.leader_speed + } else { + self.speed + }; + let to = [f64::from(at[0]), f64::from(at[1]), f64::from(at[2])]; + if !m.nav_move_to(cx.w, to, speed) { + self.move_randomly(m, cx); + state_mut(m).patrol_cooldown_until = cx.w.game_time + 200; + } else if leader { + for id in friends { + cx.events.push(MobEvent::PatrolTarget { + mob: id, + target: at, + }); + } + } + } + } +} +impl LongDistancePatrol { + fn move_randomly(&self, m: &mut Mob, cx: &mut Cx) -> bool { + let (x, z) = ( + m.position.x.floor() as i32 - 8 + m.random.next_int_bound(16).unwrap_or(0), + m.position.z.floor() as i32 - 8 + m.random.next_int_bound(16).unwrap_or(0), + ); + let at = heightmap_pos(cx.w, x, z); + m.nav_move_to( + cx.w, + [f64::from(at[0]), f64::from(at[1]), f64::from(at[2])], + self.speed, + ) + } +} +/// `Vec3i.closerToCenterThan`. +fn close_to_center(p: [i32; 3], at: Vec3, distance: f64) -> bool { + Vec3::new( + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ) + .distance_squared(at) + < distance * distance +} + +impl State { + /// A ravager carrying a raider (`hasControllingPassenger`). + pub fn has_rider(&self) -> bool { + false + } +} + +/// `Raider.HoldGroundAttackGoal`: while patrolling, stand still and let the +/// patrol shout when something shows up; attack once it comes close. +#[derive(Clone, Debug)] +pub struct HoldGroundAttack { + hostile_radius_sqr: f64, +} +impl HoldGroundAttack { + pub fn new(radius: f64) -> Self { + Self { + hostile_radius_sqr: radius * radius, + } + } +} +/// Raiders within 8 blocks, nearest first (`shoutTargeting`). +fn shout_range(m: &Mob, w: &MobWorld) -> Vec { + w.others + .iter() + .filter(|s| { + s.id != m.id + && s.alive + && is_raider(s.species) + && (s.position.x - m.position.x).abs() <= 8.0 + f64::from(m.width()) + && (s.position.y - m.position.y).abs() <= 8.0 + f64::from(m.height()) + && (s.position.z - m.position.z).abs() <= 8.0 + f64::from(m.width()) + && s.position.distance_squared(m.position) <= 64.0 + }) + .map(|s| s.id) + .collect() +} +impl Goal for HoldGroundAttack { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + let Some(s) = state(m) else { return false }; + s.raid_id.is_none() + && s.patrolling + && m.ai.target.is_some() + && !m.ai.aggressive + && m.ai.last_hurt_by != Some(Who::Player) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.ai.nav.stop(); + if let Some(target) = m.ai.target { + for id in shout_range(m, cx.w) { + cx.events.push(MobEvent::RaiderTarget { + mob: id, + target, + aggressive: false, + }); + } + } + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(target) = m.ai.target { + for id in shout_range(m, cx.w) { + cx.events.push(MobEvent::RaiderTarget { + mob: id, + target, + aggressive: true, + }); + } + m.ai.aggressive = true; + } + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(t) = m.target_info(cx.w) else { return }; + if m.distance_sqr(t.position) > self.hostile_radius_sqr { + m.look_at([t.position.x, t.eye_y, t.position.z]); + if m.random.next_int_bound(50).unwrap_or(1) == 0 { + let sound = m.kind.sounds[0]; + if !sound.is_empty() { + m.voice(sound, cx.events); + } + } + } else { + m.ai.aggressive = true; + } + } +} + +/// The saved fields (`PatrollingMonster` and `Raider.addAdditionalSaveData`). +pub fn write_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) { + let Some(s) = state(m) else { return }; + match s.patrol_target { + Some(p) => { + map.insert("patrol_target".into(), Tag::IntArray(p.to_vec())); + } + None => { + map.remove(&"patrol_target".into()); + } + } + map.insert("PatrolLeader".into(), Tag::Byte(i8::from(s.patrol_leader))); + map.insert("Patrolling".into(), Tag::Byte(i8::from(s.patrolling))); + map.insert("Wave".into(), Tag::Int(s.wave)); + map.insert("CanJoinRaid".into(), Tag::Byte(i8::from(s.can_join_raid))); + match s.raid_id { + Some(id) => { + map.insert("RaidId".into(), Tag::Int(id)); + } + None => { + map.remove(&"RaidId".into()); + } + } +} +pub fn read_nbt(m: &mut Mob, tag: &Tag) { + if !is_raider(m.species()) { + return; + } + let int = |t: Option<&Tag>| match t { + Some(Tag::Int(v)) => Some(*v), + Some(Tag::Byte(v)) => Some(i32::from(*v)), + Some(Tag::Short(v)) => Some(i32::from(*v)), + _ => None, + }; + let flag = |t: Option<&Tag>| int(t).unwrap_or(0) != 0; + let s = state_mut(m); + s.patrol_target = match tag.get("patrol_target") { + Some(Tag::IntArray(v)) if v.len() == 3 => Some([v[0], v[1], v[2]]), + _ => None, + }; + s.patrol_leader = flag(tag.get("PatrolLeader")); + s.patrolling = flag(tag.get("Patrolling")); + s.wave = int(tag.get("Wave")).unwrap_or(0); + s.can_join_raid = flag(tag.get("CanJoinRaid")); + s.raid_id = int(tag.get("RaidId")); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn raiders_and_leaders() { + assert!(is_raider(Species::Ravager) && is_raider(Species::Witch)); + assert!(!is_raider(Species::Zombie)); + assert!(can_be_leader(Species::Pillager) && can_be_leader(Species::Evoker)); + assert!(!can_be_leader(Species::Witch) && !can_be_leader(Species::Ravager)); + } + #[test] + fn long_distance_patrol_turns_by_ninety_radians() { + // PatrollingMonster passes 90.0F to Vec3.yRot (radians). + let v = y_rot(Vec3::new(10.0, 3.0, 0.0), 90.0); + let (c, s) = (90f64.cos(), 90f64.sin()); + assert!((v.x - 10.0 * c).abs() < 1e-4 && (v.z + 10.0 * s).abs() < 1e-4); + assert_eq!(v.y, 3.0); + } + #[test] + fn closer_to_center_uses_block_centres() { + let at = Vec3::new(10.5, 64.5, 10.5); + assert!(close_to_center([10, 64, 10], at, 1.0)); + assert!(!close_to_center([30, 64, 10], at, 10.0)); + } +}