From edd598cc68a68d66a850f91f82e465b422a4d0a3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 17:46:50 +0200 Subject: [PATCH] WIP: unfinished warden-sculk parity work, stopped by Ludovic Uncommitted changes the agent had in progress when it was stopped on 2026-10-12; may not build or pass its harnesses yet. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 14 +- crates/horizon-client/src/mobs.rs | 1 + crates/horizon-client/src/mobs/ai.rs | 9 +- .../horizon-client/src/mobs/villager_brain.rs | 16 +- crates/horizon-client/src/mobs/warden.rs | 1135 +++----------- .../horizon-client/src/mobs/warden_brain.rs | 1343 +++++++++++++++++ .../horizonlab/parity/VanillaMobAiOracle.java | 11 + tools/test_mob_ai_parity.py | 10 + 8 files changed, 1600 insertions(+), 939 deletions(-) create mode 100644 crates/horizon-client/src/mobs/warden_brain.rs diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 4c5178fae..4534a9ee1 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -355,7 +355,9 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) { u8::from(m.ai.jumping) ); let _ = write!(out, "\trng {:x}", m.random.state()); - if let Some((acts, mem)) = horizon_client::mobs::villager_brain::describe(m) { + if let Some((acts, mem)) = horizon_client::mobs::villager_brain::describe(m) + .or_else(|| horizon_client::mobs::warden_brain::describe(m)) + { let _ = write!(out, "\tact {acts}\tmem {mem}"); } out.push('\n'); @@ -467,6 +469,12 @@ fn main() -> horizon_client::Result<()> { match flag.as_str() { "persistent" => m.persistent = true, "noai" => m.no_ai = true, + // Warden.finalizeSpawn's own part. + "digcooldown" | "emerge" => horizon_client::mobs::warden::finalize( + &mut m, + flag == "emerge", + &mut Vec::new(), + ), other => panic!("unknown mob flag {other}"), } } @@ -481,6 +489,10 @@ fn main() -> horizon_client::Result<()> { spec.seed, ); } + if m.species() == Species::Warden { + // As for villagers: the sensors delayed again, the RunOne seeded. + horizon_client::mobs::warden::init_brain(&mut m, spec.seed); + } mobs.push(m); } let player = s.player.map(|p| { diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 5200e465b..7e08b07d8 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -58,6 +58,7 @@ pub mod vex; pub mod villager; pub mod villager_brain; pub mod warden; +pub mod warden_brain; pub mod witch; pub mod wither; mod world; diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index a5a4faaec..c87404dab 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -682,6 +682,10 @@ fn push_entities(m: &mut Mob, w: &MobWorld, events: &mut Vec) { let _ = m.random.next_int_bound(4); } for (who, at) in targets { + // Warden.doPush: touching it angers it, then the push itself. + if m.species() == Species::Warden { + super::warden::do_push(m, w, who, events); + } // Entity.push(Entity) with `this` the other entity. let (mut xa, mut za) = (m.position.x - at.x, m.position.z - at.z); let mut dd = xa.abs().max(za.abs()); @@ -758,6 +762,10 @@ fn server_ai_step( super::villager_brain::tick(m, w, level_random, events); let _ = m.random.next_int_bound(100); } + if m.species() == Species::Warden { + // Warden.customServerAiStep: the brain and its bookkeeping. + super::warden::server_ai_step(m, w, level_random, events); + } { let mut cx = Cx { w, events }; custom_server_ai_step(m, &mut cx); @@ -782,7 +790,6 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { Species::Enderman => super::enderman::custom_server_ai_step(m, cx), Species::Blaze => super::nether::blaze_server_ai_step(m, cx), Species::ElderGuardian => super::guardian::elder_server_ai_step(m, cx), - Species::Warden => super::warden::server_ai_step(m, cx), Species::Wither if m.alive() => super::wither::custom_server_ai_step(m, cx.w, cx.events), // SpellcasterIllager.customServerAiStep. Species::Evoker if m.extra.counter > 0 => m.extra.counter -= 1, diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index beb877bb1..f778ece27 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -36,7 +36,8 @@ impl Default for Slot { } } impl Slot { - fn tick(&mut self) { + /// `MemorySlot.tick` (`Brain.forgetOutdatedMemories`). + pub(super) fn tick(&mut self) { if self.v.is_some() && self.ttl != NEVER { if self.ttl <= 0 { self.clear(); @@ -66,9 +67,16 @@ impl Slot { pub fn get(&self) -> Option<&T> { self.v.as_ref() } + pub(super) fn get_mut(&mut self) -> Option<&mut T> { + self.v.as_mut() + } pub fn present(&self) -> bool { self.v.is_some() } + /// The time to live (`i64::MAX`: never expires). + pub fn ttl(&self) -> i64 { + self.ttl + } } impl Slot { pub fn value(&self) -> Option { @@ -77,7 +85,7 @@ impl Slot { } impl Slot> { /// `Brain.setMemory` of a collection: an empty one erases the memory. - fn set_list(&mut self, v: Vec) { + pub(super) fn set_list(&mut self, v: Vec) { if v.is_empty() { self.clear(); } else { @@ -162,8 +170,8 @@ impl WalkTarget { /// cache of `Sensor.isEntityTargetable`. #[derive(Clone, Debug, Default)] pub struct Visible { - list: Vec, - cache: Vec<(Who, bool)>, + pub(super) list: Vec, + pub(super) cache: Vec<(Who, bool)>, } /// The memories a villager's brain registers. diff --git a/crates/horizon-client/src/mobs/warden.rs b/crates/horizon-client/src/mobs/warden.rs index 11394a011..44ef96dd0 100644 --- a/crates/horizon-client/src/mobs/warden.rs +++ b/crates/horizon-client/src/mobs/warden.rs @@ -1,34 +1,23 @@ -//! The warden (`Warden`, `WardenAi`, `AngerManagement`): a brain with the -//! emerge, dig, roar, fight, investigate, sniff and idle activities, anger -//! kept per entity, vibration listening, the sonic boom, the heartbeat and -//! tendril animations, and digging back into the ground when nothing has -//! disturbed it for a minute. +//! The warden (`Warden`, `AngerManagement`): anger kept per entity, +//! vibration listening, the sonic boom and melee attack, the heartbeat and +//! tendril animations, the model and its emissive layers. Its brain +//! (`WardenAi`) is in `warden_brain`. use super::{ Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, anim::{Poses, State}, - goals::{Cx, Float}, keyframes::Animation, - path::{Path, PathType}, + path::PathType, + warden_brain::{self, Brain}, }; use crate::sculk::{self, Context, Info}; use horizon_core::{ geometry::{Vec3, trig::Mth}, - random::RandomSource, + random::{LegacyRandom, RandomSource}, }; use std::{collections::HashMap, f32::consts::PI}; -pub const EMERGE_DURATION: i64 = 134; -pub const ROAR_DURATION: i64 = 84; -const ROAR_SOUND_DELAY: i64 = 25; -const SNIFFING_DURATION: i64 = 84; -const DIGGING_DURATION: i64 = 100; -pub const DIGGING_COOLDOWN: i64 = 1200; -const MELEE_ATTACK_COOLDOWN: i64 = 18; -const SONIC_DURATION: i64 = 60; -const SONIC_SOUND_DELAY: i64 = 34; -const SPEED_IDLING: f64 = 0.5; -const SPEED_INVESTIGATING: f64 = 0.7; -const SPEED_FIGHTING: f64 = 1.2; +pub const EMERGE_DURATION: i64 = warden_brain::EMERGE_DURATION as i64; +pub const DIGGING_COOLDOWN: i64 = warden_brain::DIGGING_COOLDOWN; const DEFAULT_ANGER: i32 = 35; const PROJECTILE_ANGER: i32 = 10; const ON_HURT_ANGER_BOOST: i32 = 20; @@ -87,7 +76,7 @@ pub fn digging_or_emerging(m: &Mob) -> bool { matches!(pose(m), Pose::Digging | Pose::Emerging) } /// `Entity.setPose`, with `onSyncedDataUpdated` starting the keyframes. -fn set_pose(m: &mut Mob, new: Pose) { +pub(super) fn set_pose(m: &mut Mob, new: Pose) { if pose(m) == new { return; } @@ -236,142 +225,20 @@ impl AngerManagement { } } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Activity { - Emerge, - Dig, - Roar, - Fight, - Investigate, - Sniff, - Idle, -} -#[derive(Clone, Copy, Debug, PartialEq)] -enum Track { - Block([i32; 3]), - /// An entity, tracked at its eyes when the flag is set. - Entity(Who, bool), -} -#[derive(Clone, Copy, Debug, PartialEq)] -struct Walk { - target: Track, - speed: f32, - close_enough: i32, -} -/// `MoveToTargetSink`'s running state. +/// The warden's state: anger, its vibration listener and its brain. #[derive(Clone, Debug, Default)] -struct MoveSink { - end: i64, - last_target: [i32; 3], - speed: f32, - path: Option, -} -/// `RunOne` over the idle stroll and `DoNothing`. -#[derive(Clone, Copy, Debug, Default)] -struct Pause { - end: i64, -} - -/// The warden's brain and sensors. -#[derive(Clone, Debug)] pub struct Warden { pub anger: AngerManagement, pub vibration: sculk::Data, - activity: Activity, - in_brain: bool, - // Memories: the game time they stop being present (None: absent). - dig_cooldown: Option, - is_emerging: Option, - sniffing: bool, - sniff_cooldown: Option, - roar_target: Option, - attack_target: Option, - disturbance: Option<([i32; 3], i64)>, - look: Option<(Track, i64)>, - walk: Option, - cant_reach_since: Option, - vibration_cooldown: Option, - touch_cooldown: Option, - recent_projectile: Option, - roar_sound_delay: Option, - roar_sound_cooldown: Option, - sonic_cooldown: Option, - sonic_sound_delay: Option, - sonic_sound_cooldown: Option, - attack_cooling_down: Option, - nearest_living: Vec, - nearest_attackable: Option, - sensor_timer: i32, - // Running behaviours (the game time they time out). - emerging: Option, - digging: Option, - roaring: Option, - sniffing_run: Option, - sonic: Option, - look_sink: Option, - move_sink: Option, - move_cooldown: i32, - pause: Option, + pub brain: Brain, /// `getClientAngerLevel`, synchronised once a second. pub client_anger: i32, - /// Attackers noted by `hurtServer` and not yet handled by the brain. + /// Attackers noted by `hurtServer` and not yet reacted to. hurt_by: Vec<(Option, bool)>, } -const NEVER: i64 = i64::MAX; -impl Default for Warden { - fn default() -> Self { - Self { - anger: AngerManagement::default(), - vibration: sculk::Data::default(), - activity: Activity::Idle, - in_brain: false, - dig_cooldown: None, - is_emerging: None, - sniffing: false, - sniff_cooldown: None, - roar_target: None, - attack_target: None, - disturbance: None, - look: None, - walk: None, - cant_reach_since: None, - vibration_cooldown: None, - touch_cooldown: None, - recent_projectile: None, - roar_sound_delay: None, - roar_sound_cooldown: None, - sonic_cooldown: None, - sonic_sound_delay: None, - sonic_sound_cooldown: None, - attack_cooling_down: None, - nearest_living: Vec::new(), - nearest_attackable: None, - sensor_timer: 0, - emerging: None, - digging: None, - roaring: None, - sniffing_run: None, - sonic: None, - look_sink: None, - move_sink: None, - move_cooldown: 0, - pause: None, - client_anger: 0, - hurt_by: Vec::new(), - } - } -} -fn present(memory: Option, now: i64) -> bool { - memory.is_some_and(|until| now < until) -} impl Warden { - /// `Brain.setMemoryWithExpiry`: present for `ttl` brain ticks; set - /// outside the brain's tick it loses the one it ticks at once. - fn expiry(&self, now: i64, ttl: i64) -> Option { - Some(now + ttl - i64::from(!self.in_brain)) - } pub fn target(&self) -> Option { - self.attack_target + self.brain.mem.attack_target.value() } } @@ -384,38 +251,40 @@ pub fn register(m: &mut Mob) { m.set_malus(PathType::Lava, 8.0); m.set_malus(PathType::Fire, 0.0); m.set_malus(PathType::FireInNeighbor, 0.0); - // Swim(0.8) is part of the brain's core activity. - m.ai.goals.add(0, Float); - // The sensors scan on a random phase. - let phase = m.random.next_int_bound(20).unwrap_or(0); - if let Some(w) = m.extra.warden.as_mut() { - w.sensor_timer = phase; + // Brain.Provider.makeBrain: the sensors start on a random phase. + delay_sensors(m); +} +/// `Sensor.randomlyDelayStart` for the warden's two sensors, from its random. +pub fn delay_sensors(m: &mut Mob) { + if let Some(mut st) = m.extra.warden.take() { + st.brain.delay_sensors(&mut m.random); + m.extra.warden = Some(st); } } -/// `Sensor.randomlyDelayStart` for the warden's sensors, in brain order -/// (`NEAREST_PLAYERS`, then `WARDEN_ENTITY_SENSOR`, which sets the phase of -/// the combined scan here). -pub fn delay_sensors(m: &mut Mob) { - if m.species() != Species::Warden { - return; - } - let _players = m.random.next_int_bound(20).unwrap_or(0); - let entities = m.random.next_int_bound(20).unwrap_or(0); - if let Some(w) = m.extra.warden.as_mut() { - w.sensor_timer = entities; +/// A brain whose `RunOne` shuffles with `seed` (vanilla seeds it from the +/// clock; harnesses seed both sides alike), its sensors delayed again. +pub fn init_brain(m: &mut Mob, seed: i64) { + if let Some(st) = m.extra.warden.as_mut() { + let mem = std::mem::take(&mut st.brain.mem); + st.brain = Brain::new(seed); + st.brain.mem = mem; } + delay_sensors(m); } /// `Warden.finalizeSpawn`: a minute until it digs back down; a summoned /// warden climbs out of the ground first. pub fn finalize(m: &mut Mob, triggered: bool, events: &mut Vec) { - let now = i64::from(m.age); - let Some(st) = m.extra.warden.as_mut() else { + if m.extra.warden.is_none() { return; - }; - st.dig_cooldown = Some(now + DIGGING_COOLDOWN); + } + warden_brain::mem(m) + .dig_cooldown + .set_ttl((), DIGGING_COOLDOWN); if triggered { - st.is_emerging = Some(now + EMERGE_DURATION); set_pose(m, Pose::Emerging); + warden_brain::mem(m) + .is_emerging + .set_ttl((), EMERGE_DURATION); sound(m, "entity.warden.agitated", 5.0, 1.0, events); } } @@ -431,15 +300,19 @@ fn voice_pitch(m: &mut Mob) -> f32 { } fn closer_than(m: &Mob, p: Vec3, horizontal: f64, vertical: f64) -> bool { let (dx, dy, dz) = (p.x - m.position.x, p.y - m.position.y, p.z - m.position.z); - dx * dx + dz * dz < horizontal * horizontal && dy.abs() < vertical + dx * dx + dz * dz < horizontal * horizontal && dy * dy < vertical * vertical } // ---- entity facts ---- -/// `Warden.canTargetEntity`. +/// `Warden.canTargetEntity`: living, neither creative nor spectator, not a +/// warden, alive. pub fn can_target(w: &MobWorld, who: Who) -> bool { match who { - Who::Player => w.player.as_ref().is_some_and(|p| p.alive && !p.creative), + Who::Player => w + .player + .as_ref() + .is_some_and(|p| p.alive && !p.creative && !p.spectator), Who::Mob(id) => w .seen(id) .is_some_and(|s| s.alive && s.species != Species::Warden), @@ -448,54 +321,12 @@ pub fn can_target(w: &MobWorld, who: Who) -> bool { fn position_of(w: &MobWorld, who: Who) -> Option { w.target_info(who).map(|t| t.position) } -fn track_position(w: &MobWorld, track: Track) -> Option<[f64; 3]> { - match track { - Track::Block(p) => Some([ - f64::from(p[0]) + 0.5, - f64::from(p[1]) + 0.5, - f64::from(p[2]) + 0.5, - ]), - Track::Entity(who, eyes) => w.target_info(who).map(|t| { - [ - t.position.x, - if eyes { t.eye_y } else { t.position.y }, - t.position.z, - ] - }), - } -} -fn track_block(w: &MobWorld, track: Track) -> Option<[i32; 3]> { - match track { - Track::Block(p) => Some(p), - Track::Entity(who, _) => w.target_info(who).map(|t| { - [ - t.position.x.floor() as i32, - t.position.y.floor() as i32, - t.position.z.floor() as i32, - ] - }), - } -} -fn block_pos(m: &Mob) -> [i32; 3] { - [ - m.position.x.floor() as i32, - m.position.y.floor() as i32, - m.position.z.floor() as i32, - ] -} -fn manhattan(a: [i32; 3], b: [i32; 3]) -> i32 { - (a[0] - b[0]).abs() + (a[1] - b[1]).abs() + (a[2] - b[2]).abs() -} -fn dist_sqr(a: [i32; 3], b: [i32; 3]) -> f64 { - (0..3).map(|i| f64::from(a[i] - b[i]).powi(2)).sum() -} // ---- anger ---- /// `Warden.increaseAngerAt`. -fn increase_anger( +pub(super) fn increase_anger( m: &mut Mob, - st: &mut Warden, w: &MobWorld, who: Option, amount: i32, @@ -503,62 +334,39 @@ fn increase_anger( events: &mut Vec, ) { let Some(who) = who else { return }; - if !can_target(w, who) { + if m.no_ai || !can_target(w, who) { return; } - set_dig_cooldown(st, i64::from(m.age)); - let maybe_switch = st.attack_target != Some(Who::Player); + warden_brain::set_dig_cooldown(m); + let Some(st) = m.extra.warden.as_mut() else { + return; + }; + let maybe_switch = st.target() != Some(Who::Player); let new = st.anger.increase(who, amount); if who == Who::Player && maybe_switch && AngerLevel::by_anger(new).is_angry() { - st.attack_target = None; + st.brain.mem.attack_target.clear(); } if play_sound && pose(m) != Pose::Roaring { - let level = angry_level(st); + let level = anger_level(m); let pitch = voice_pitch(m); sound(m, level.listening_sound(), 10.0, pitch, events); } } -fn angry_level(st: &Warden) -> AngerLevel { - AngerLevel::by_anger(st.anger.active_anger(st.attack_target)) -} /// `Warden.getEntityAngryAt`. -fn entity_angry_at(st: &Warden, w: &MobWorld) -> Option { - if angry_level(st).is_angry() { +pub(super) fn entity_angry_at(m: &Mob, w: &MobWorld) -> Option { + let st = m.extra.warden.as_ref()?; + if anger_level(m).is_angry() { st.anger.active_entity(|e| can_target(w, e)) } else { None } } -/// `Warden.getAngerLevel` of a warden (for its ambient sound). +/// `Warden.getAngerLevel`. pub fn anger_level(m: &Mob) -> AngerLevel { m.extra.warden.as_ref().map_or(AngerLevel::Calm, |s| { - AngerLevel::by_anger(s.anger.active_anger(s.attack_target)) + AngerLevel::by_anger(s.anger.active_anger(s.target())) }) } -/// `WardenAi.setDigCooldown`. -fn set_dig_cooldown(st: &mut Warden, now: i64) { - if present(st.dig_cooldown, now) { - st.dig_cooldown = st.expiry(now, DIGGING_COOLDOWN); - } -} -/// `WardenAi.setDisturbanceLocation`. -fn set_disturbance(st: &mut Warden, w: &MobWorld, now: i64, position: [i32; 3]) { - if entity_angry_at(st, w).is_none() && st.attack_target.is_none() { - set_dig_cooldown(st, now); - st.sniff_cooldown = st.expiry(now, 100); - let until = st.expiry(now, 100).unwrap_or(now); - st.look = Some((Track::Block(position), until)); - st.disturbance = Some((position, until)); - st.walk = None; - } -} -/// `Warden.setAttackTarget`. -fn set_attack_target(st: &mut Warden, target: Who, now: i64) { - st.roar_target = None; - st.attack_target = Some(target); - st.cant_reach_since = None; - st.sonic_cooldown = st.expiry(now, 200); -} // ---- damage ---- @@ -566,9 +374,9 @@ fn set_attack_target(st: &mut Warden, target: Who, now: i64) { pub fn accepts_damage(m: &Mob, source: &Damage) -> bool { !(digging_or_emerging(m) && source.kind != DamageKind::Generic) } -/// `Warden.hurtServer`'s reaction, handled by the brain's next tick. +/// `Warden.hurtServer`'s reaction, handled at the warden's next tick. pub fn hurt(m: &mut Mob, source: &Damage) { - if digging_or_emerging(m) { + if m.no_ai || digging_or_emerging(m) { return; } let direct = !matches!( @@ -579,32 +387,79 @@ pub fn hurt(m: &mut Mob, source: &Damage) { st.hurt_by.push((source.attacker, direct)); } } +/// The rest of `Warden.hurtServer`. +fn handle_hurt(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + let hurt = m + .extra + .warden + .as_mut() + .map(|st| std::mem::take(&mut st.hurt_by)) + .unwrap_or_default(); + for (attacker, direct) in hurt { + increase_anger( + m, + w, + attacker, + AngerLevel::Angry.minimum() + ON_HURT_ANGER_BOOST, + false, + events, + ); + if !warden_brain::mem(m).attack_target.present() + && let Some(who) = attacker + && let Some(p) = position_of(w, who) + && (direct || m.distance_sqr(p) < 25.0) + { + warden_brain::set_attack_target(m, who); + } + } +} +/// `Warden.doPush`: touching something angers it (once a second). +pub fn do_push(m: &mut Mob, w: &MobWorld, who: Who, events: &mut Vec) { + if m.no_ai || m.extra.warden.is_none() || warden_brain::mem(m).touch_cooldown.present() { + return; + } + warden_brain::mem(m).touch_cooldown.set_ttl((), 20); + increase_anger(m, w, Some(who), DEFAULT_ANGER, true, events); + if let Some(t) = w.target_info(who) { + let block = [ + t.position.x.floor() as i32, + t.position.y.floor() as i32, + t.position.z.floor() as i32, + ]; + warden_brain::set_disturbance(m, w, block); + } +} +/// `Warden.doHurtTarget`: the attack keyframes (entity event 4), the impact +/// sound, a sonic boom cooldown, then `Mob.doHurtTarget`. +pub(super) fn do_hurt_target(m: &mut Mob, target: Who, w: &MobWorld, events: &mut Vec) { + m.anim.states[ROAR].stop(); + m.anim.states[ATTACK].start(m.age as f32); + let pitch = voice_pitch(m); + sound(m, "entity.warden.attack_impact", 10.0, pitch, events); + warden_brain::mem(m).sonic_boom_cooldown.set_ttl((), 40); + let mut cx = warden_brain::cx(w, events); + super::ai::do_hurt_target(m, target, &mut cx); +} // ---- vibrations ---- /// `Warden.VibrationUser.canReceiveVibration`. -pub fn can_receive_vibration(m: &Mob, now: i64, ctx: &Context) -> bool { +pub fn can_receive_vibration(m: &Mob, _now: i64, ctx: &Context) -> bool { let Some(st) = m.extra.warden.as_ref() else { return false; }; - m.alive() - && !present(st.vibration_cooldown, now) + !m.no_ai + && m.alive() + && !st.brain.mem.vibration_cooldown.present() && !digging_or_emerging(m) && !(ctx.living && !ctx.targetable) } /// `Warden.VibrationUser.onReceiveVibration`. -fn receive_vibration( - m: &mut Mob, - st: &mut Warden, - w: &MobWorld, - info: Info, - events: &mut Vec, -) { +fn receive_vibration(m: &mut Mob, w: &MobWorld, info: Info, events: &mut Vec) { if !m.alive() { return; } - let now = i64::from(m.age); - st.vibration_cooldown = st.expiry(now, 40); + warden_brain::mem(m).vibration_cooldown.set_ttl((), 40); // Entity event 61: the tendrils twitch. m.anim.v[TENDRIL] = 10.0; let pitch = voice_pitch(m); @@ -617,9 +472,9 @@ fn receive_vibration( let mut suspicious = origin; if let Some(owner) = info.owner { if let Some(p) = position_of(w, owner) - && closer_than_distance(m, p, 30.0) + && m.distance_sqr(p) < 900.0 { - if present(st.recent_projectile, now) { + if warden_brain::mem(m).recent_projectile.present() { if can_target(w, owner) && let Some(t) = w.target_info(owner) { @@ -629,585 +484,97 @@ fn receive_vibration( t.position.z.floor() as i32, ]; } - increase_anger(m, st, w, Some(owner), DEFAULT_ANGER, true, events); + increase_anger(m, w, Some(owner), DEFAULT_ANGER, true, events); } else { - increase_anger(m, st, w, Some(owner), PROJECTILE_ANGER, true, events); + increase_anger(m, w, Some(owner), PROJECTILE_ANGER, true, events); } } - st.recent_projectile = st.expiry(now, 100); + warden_brain::mem(m).recent_projectile.set_ttl((), 100); } else { - increase_anger(m, st, w, info.source, DEFAULT_ANGER, true, events); + increase_anger(m, w, info.source, DEFAULT_ANGER, true, events); } - if !angry_level(st).is_angry() { - let active = st.anger.active_entity(|e| can_target(w, e)); + if !anger_level(m).is_angry() { + let active = m + .extra + .warden + .as_ref() + .and_then(|st| st.anger.active_entity(|e| can_target(w, e))); if info.owner.is_some() || active.is_none() || active == info.source { - set_disturbance(st, w, now, suspicious); + warden_brain::set_disturbance(m, w, suspicious); } } } -fn closer_than_distance(m: &Mob, p: Vec3, distance: f64) -> bool { - m.distance_sqr(p) < distance * distance -} -// ---- the brain ---- +// ---- the server tick ---- -/// `Warden.customServerAiStep`: the vibration ticker, the brain, darkness, -/// anger and the activity. -pub fn server_ai_step(m: &mut Mob, cx: &mut Cx) { - let Some(mut st) = m.extra.warden.take() else { +/// `Warden.tick` (the vibration ticker, persistence keeping the dig +/// cooldown) and `Warden.customServerAiStep` (the brain, the darkness +/// pulse, anger and the activity). +pub fn server_ai_step( + m: &mut Mob, + w: &MobWorld, + level_random: &mut LegacyRandom, + events: &mut Vec, +) { + if m.extra.warden.is_none() { return; - }; - let now = i64::from(m.age); - // Warden.tick: vibrations arrive before the brain thinks. - st.in_brain = false; - if st.dig_cooldown.is_some() && m.custom_name.is_some() { - set_dig_cooldown(&mut st, now); } - let tick = st - .vibration - .tick(cx.w.game_time, true, false, |d| d.floor() as i32); + let tick = m + .extra + .warden + .as_mut() + .map(|st| st.vibration.tick(w.game_time, true, false, |d| d.floor() as i32)) + .unwrap_or_default(); if let Some((info, travel)) = tick.started { let eye = [m.position.x, m.position.y + m.kind.eye_height, m.position.z]; - cx.events.push(MobEvent::Vibration { + events.push(MobEvent::Vibration { from: info.pos, to: eye, ticks: travel, }); } if let Some(info) = tick.received { - receive_vibration(m, &mut st, cx.w, info, cx.events); + receive_vibration(m, w, info, events); } - touch_entities(m, &mut st, cx); - handle_hurt(m, &mut st, cx); - st.in_brain = true; - brain_tick(m, &mut st, cx); - st.in_brain = false; - // Warden.customServerAiStep after the brain. + if m.persistent || m.custom_name.is_some() { + warden_brain::set_dig_cooldown(m); + } + handle_hurt(m, w, events); + warden_brain::tick(m, w, level_random, events); if (i64::from(m.age) + i64::from(m.id)) % 120 == 0 { - cx.events.push(MobEvent::Darkness { - at: [m.position.x, m.position.y, m.position.z], + events.push(MobEvent::Darkness { + at: at(m), radius: DARKNESS_RADIUS, }); } - if m.age.is_multiple_of(20) { - let w = cx.w; + if m.age.is_multiple_of(20) + && let Some(st) = m.extra.warden.as_mut() + { st.anger.tick(|who| can_target(w, who)); - st.client_anger = st.anger.active_anger(st.attack_target); + st.client_anger = st.anger.active_anger(st.target()); } - update_activity(m, &mut st, now); - m.extra.warden = Some(st); -} -/// `Warden.doPush`: touching something angers it (every second). -fn touch_entities(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - if digging_or_emerging(m) || !m.alive() { - return; - } - let now = i64::from(m.age); - if present(st.touch_cooldown, now) { - return; - } - let bounds = m.bounds(); - let mut touched = None; - if let Some(p) = cx.w.player.as_ref() - && p.alive - && !p.spectator - && bounds.intersects(p.bounds) - { - touched = Some(Who::Player); - } - if touched.is_none() { - touched = - cx.w.others - .iter() - .find(|s| s.id != m.id && s.alive && bounds.intersects(s.bounds)) - .map(|s| Who::Mob(s.id)); - } - if let Some(who) = touched { - st.touch_cooldown = st.expiry(now, 20); - increase_anger(m, st, cx.w, Some(who), DEFAULT_ANGER, true, cx.events); - if let Some(t) = cx.w.target_info(who) { - let block = [ - t.position.x.floor() as i32, - t.position.y.floor() as i32, - t.position.z.floor() as i32, - ]; - set_disturbance(st, cx.w, now, block); - } + if let Some(st) = m.extra.warden.as_mut() { + st.brain.update_activity(); } } -/// The rest of `Warden.hurtServer`. -fn handle_hurt(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - for (attacker, direct) in std::mem::take(&mut st.hurt_by) { - increase_anger( - m, - st, - cx.w, - attacker, - AngerLevel::Angry.minimum() + ON_HURT_ANGER_BOOST, - false, - cx.events, - ); - if st.attack_target.is_none() - && let Some(who) = attacker - && let Some(p) = position_of(cx.w, who) - && (direct || closer_than_distance(m, p, 5.0)) - { - set_attack_target(st, who, i64::from(m.age)); - } - } -} -/// `Brain.setActiveActivityToFirstValid`, erasing the memories of the -/// activity being left. -fn update_activity(m: &mut Mob, st: &mut Warden, now: i64) { - let _ = m; - let next = if present(st.is_emerging, now) { - Activity::Emerge - } else if st.roar_target.is_none() && !present(st.dig_cooldown, now) { - Activity::Dig - } else if st.roar_target.is_some() { - Activity::Roar - } else if st.attack_target.is_some() { - Activity::Fight - } else if st.disturbance.is_some_and(|(_, until)| now < until) { - Activity::Investigate - } else if st.sniffing { - Activity::Sniff - } else { - Activity::Idle - }; - if next != st.activity { - match st.activity { - Activity::Emerge => st.is_emerging = None, - Activity::Roar => st.roar_target = None, - Activity::Fight => st.attack_target = None, - Activity::Investigate => st.disturbance = None, - Activity::Sniff => st.sniffing = false, - Activity::Dig | Activity::Idle => {} - } - st.activity = next; - } -} -fn active(st: &Warden, activity: Activity) -> bool { - st.activity == activity -} -fn brain_tick(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - let now = i64::from(m.age); - // Memories that timed out are forgotten. - if st.disturbance.is_some_and(|(_, until)| now >= until) { - st.disturbance = None; - } - if st.look.is_some_and(|(_, until)| now >= until) { - st.look = None; - } - sense(m, st, cx.w); - start_behaviours(m, st, cx); - tick_behaviours(m, st, cx); -} -/// `WardenEntitySensor` (and `NearestLivingEntitySensor`) every 20 ticks. -fn sense(m: &mut Mob, st: &mut Warden, w: &MobWorld) { - st.sensor_timer -= 1; - if st.sensor_timer > 0 { - return; - } - st.sensor_timer = 20; - let range = m.attrs.follow_range; - let area = m - .bounds() - .inflate(horizon_core::geometry::Vec3::new(range, range, range)); - let mut found: Vec<(Who, f64)> = Vec::new(); - if let Some(p) = w.player.as_ref() - && p.alive - && area.intersects(p.bounds) - { - found.push((Who::Player, m.distance_sqr(p.position))); - } - for s in w.others { - if s.id != m.id && s.alive && area.intersects(s.bounds) { - found.push((Who::Mob(s.id), m.distance_sqr(s.position))); - } - } - found.sort_by(|a, b| a.1.total_cmp(&b.1)); - st.nearest_living = found.into_iter().map(|(who, _)| who).collect(); - let closest = |players: bool| { - st.nearest_living - .iter() - .copied() - .find(|who| can_target(w, *who) && (*who == Who::Player) == players) - }; - let attackable = closest(true).or_else(|| closest(false)); - st.nearest_attackable = attackable; -} -/// `NearestVisibleLivingEntities.contains`. -fn visible(m: &mut Mob, st: &Warden, w: &MobWorld, who: Who) -> bool { - st.nearest_living.contains(&who) && m.sees(w, who) -} - -fn start_behaviours(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - let now = i64::from(m.age); - // Core: SetWardenLookTarget. - if st.attack_target.is_none() { - let target = st - .roar_target - .and_then(|who| track_block(cx.w, Track::Entity(who, true))) - .or(st.disturbance.map(|(p, _)| p)); - if let Some(p) = target { - st.look = Some((Track::Block(p), NEVER)); - } - } - // Dig: Digging. - if active(st, Activity::Dig) - && st.digging.is_none() - && st.attack_target.is_none() - && st.walk.is_none() - && (m.on_ground || m.is_in_liquid()) - { - st.digging = Some(now + DIGGING_DURATION); - if m.on_ground { - set_pose(m, Pose::Digging); - sound(m, "entity.warden.dig", 5.0, 1.0, cx.events); - } else { - sound(m, "entity.warden.agitated", 5.0, 1.0, cx.events); - stop_digging(m, st); - } - } - // Core: LookAtTargetSink. - if st.look_sink.is_none() && st.look.is_some() { - let duration = 45 + i64::from(m.random.next_int_bound(46).unwrap_or(0)); - st.look_sink = Some(now + duration); - } - // Core: MoveToTargetSink. - if st.move_sink.is_none() && st.walk.is_some() { - start_move_sink(m, st, cx); - } - // Emerge: Emerging. - if active(st, Activity::Emerge) - && st.emerging.is_none() - && present(st.is_emerging, now) - && st.walk.is_none() - { - st.emerging = Some(now + EMERGE_DURATION); - set_pose(m, Pose::Emerging); - sound(m, "entity.warden.emerge", 5.0, 1.0, cx.events); - } - // SetRoarTarget (investigate, sniff and idle). - if matches!( - st.activity, - Activity::Investigate | Activity::Sniff | Activity::Idle - ) && st.roar_target.is_none() - && st.attack_target.is_none() - && let Some(target) = entity_angry_at(st, cx.w).filter(|t| can_target(cx.w, *t)) - { - st.roar_target = Some(target); - st.cant_reach_since = None; - } - // Investigate: GoToTargetLocation. - if active(st, Activity::Investigate) - && st.attack_target.is_none() - && st.walk.is_none() - && let Some((location, until)) = st.disturbance - && now < until - && dist_sqr(location, block_pos(m)) >= 4.0 - { - let ox = m.random.next_int_bound(3).unwrap_or(1) - 1; - let oz = m.random.next_int_bound(3).unwrap_or(1) - 1; - let target = [location[0] + ox, location[1], location[2] + oz]; - st.look = Some((Track::Block(target), NEVER)); - st.walk = Some(Walk { - target: Track::Block(target), - speed: SPEED_INVESTIGATING as f32, - close_enough: 2, - }); - } - // Sniff: Sniffing. - if active(st, Activity::Sniff) - && st.sniffing_run.is_none() - && st.sniffing - && st.attack_target.is_none() - && st.walk.is_none() - { - st.sniffing_run = Some(now + SNIFFING_DURATION); - sound(m, "entity.warden.sniff", 5.0, 1.0, cx.events); - } - // Roar. - if active(st, Activity::Roar) - && st.roaring.is_none() - && let Some(target) = st.roar_target - && st.attack_target.is_none() - { - st.roaring = Some(now + ROAR_DURATION); - st.roar_sound_delay = st.expiry(now, ROAR_SOUND_DELAY); - st.walk = None; - st.look = Some((Track::Entity(target, true), NEVER)); - set_pose(m, Pose::Roaring); - increase_anger(m, st, cx.w, Some(target), 20, false, cx.events); - } - // Fight: the dig cooldown setter. - if active(st, Activity::Fight) { - set_dig_cooldown(st, now); - } - // Idle: TryToSniff. - if active(st, Activity::Idle) - && !present(st.sniff_cooldown, now) - && st.nearest_attackable.is_some() - && st.disturbance.is_none() - { - st.sniffing = true; - let cooldown = 100 + i64::from(m.random.next_int_bound(101).unwrap_or(0)); - st.sniff_cooldown = st.expiry(now, cooldown); - st.walk = None; - set_pose(m, Pose::Sniffing); - } - // Fight: StopAttackingIfTargetInvalid. - if active(st, Activity::Fight) - && let Some(target) = st.attack_target - { - let tired = st.cant_reach_since.is_some_and(|since| now - since > 200); - let valid = can_target(cx.w, target) - && !tired - && cx.w.target_info(target).is_some_and(|t| t.alive) - && angry_level(st).is_angry(); - if !valid { - if !can_target(cx.w, target) { - st.anger.clear(target); - } - set_dig_cooldown(st, now); - st.attack_target = None; - } - } - // Idle: RunOne over the stroll and DoNothing. - if active(st, Activity::Idle) && st.pause.is_none() && !st.sniffing { - run_one(m, st, cx); - } - // Fight: SetEntityLookTarget. - if active(st, Activity::Fight) - && st.look.is_none() - && let Some(target) = st.attack_target - && visible(m, st, cx.w, target) - && position_of(cx.w, target) - .is_some_and(|p| m.distance_sqr(p) <= m.attrs.follow_range * m.attrs.follow_range) - { - st.look = Some((Track::Entity(target, true), NEVER)); - } - // Fight: SetWalkTargetFromAttackTargetIfTargetOutOfReach. - if active(st, Activity::Fight) - && let Some(target) = st.attack_target - { - let in_reach = visible(m, st, cx.w, target) - && cx - .w - .target_info(target) - .is_some_and(|t| m.within_melee_range(&t)); - if in_reach { - st.walk = None; - } else { - st.look = Some((Track::Entity(target, true), NEVER)); - st.walk = Some(Walk { - target: Track::Entity(target, false), - speed: SPEED_FIGHTING as f32, - close_enough: 0, - }); - } - } - // Fight: SonicBoom. - if active(st, Activity::Fight) - && st.sonic.is_none() - && !present(st.sonic_cooldown, now) - && let Some(target) = st.attack_target - && position_of(cx.w, target).is_some_and(|p| closer_than(m, p, 15.0, 20.0)) - { - st.sonic = Some(now + SONIC_DURATION); - st.attack_cooling_down = st.expiry(now, SONIC_DURATION); - st.sonic_sound_delay = st.expiry(now, SONIC_SOUND_DELAY); - m.anim.states[SONIC_BOOM].start(m.age as f32); - sound(m, "entity.warden.sonic_charge", 3.0, 1.0, cx.events); - } - // Fight: MeleeAttack. - if active(st, Activity::Fight) - && !present(st.attack_cooling_down, now) - && let Some(target) = st.attack_target - && visible(m, st, cx.w, target) - && let Some(info) = cx.w.target_info(target) - && m.within_melee_range(&info) - { - st.look = Some((Track::Entity(target, true), NEVER)); - m.swing(); - attack(m, target, cx); - st.attack_cooling_down = st.expiry(now, MELEE_ATTACK_COOLDOWN); - // SonicBoom.setCooldown(this, 40) from doHurtTarget. - st.sonic_cooldown = st.expiry(now, 40); - m.anim.states[ROAR].stop(); - m.anim.states[ATTACK].start(m.age as f32); - } -} -/// `Warden.doHurtTarget`: the hit, its impact sound and the knockback. -fn attack(m: &mut Mob, target: Who, cx: &mut Cx) { - let pitch = voice_pitch(m); - sound(m, "entity.warden.attack_impact", 10.0, pitch, cx.events); - super::ai::do_hurt_target(m, target, cx); - // ATTACK_KNOCKBACK 1.5: half of it, along the warden's facing. - let yaw = m.yaw.to_radians(); - cx.events.push(MobEvent::Push { - target, - velocity: [ - -f64::from(yaw.sin()) * 0.75, - 0.0, - f64::from(yaw.cos()) * 0.75, - ], - }); - m.velocity.x *= 0.6; - m.velocity.z *= 0.6; -} -/// `RunOne`: a stroll (weight 2) or a pause (weight 1), picked by shuffling. -fn run_one(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - let now = i64::from(m.age); - // ShufflingList.shuffle: each entry sorts by -ln(random) / weight. - let stroll_key = -f64::from(m.random.next_float()).ln() / 2.0; - let pause_key = -f64::from(m.random.next_float()).ln(); - let pause_first = pause_key < stroll_key; - let order = if pause_first { - [false, true] - } else { - [true, false] - }; - for stroll in order { - if stroll { - // RandomStroll.stroll(0.5): only when there is no walk target. - if st.walk.is_none() { - st.walk = m.land_random_pos(cx.w, 10, 7).map(|p| Walk { - target: Track::Block([ - p[0].floor() as i32, - p[1].floor() as i32, - p[2].floor() as i32, - ]), - speed: SPEED_IDLING as f32, - close_enough: 0, - }); - return; - } - } else { - let duration = 30 + i64::from(m.random.next_int_bound(31).unwrap_or(0)); - st.pause = Some(Pause { - end: now + duration, - }); - return; - } - } -} -fn stop_digging(m: &mut Mob, st: &mut Warden) { - st.digging = None; - // Digging.stop: the warden is removed. - m.removed = true; -} - -fn tick_behaviours(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - let now = i64::from(m.age); - // LookAtTargetSink. - if let Some(end) = st.look_sink { - let keep = now <= end - && st.look.is_some_and(|(track, _)| match track { - Track::Block(_) => true, - Track::Entity(who, _) => visible(m, st, cx.w, who), - }); - if keep { - if let Some((track, _)) = st.look - && let Some(p) = track_position(cx.w, track) - { - m.look_at(p); - } - } else { - st.look_sink = None; - st.look = None; - } - } - // MoveToTargetSink. - tick_move_sink(m, st, cx); - // Emerging. - if let Some(end) = st.emerging - && now > end - { - st.emerging = None; - if pose(m) == Pose::Emerging { - set_pose(m, Pose::Standing); - } - } - // Digging: removed when the time is up. - if let Some(end) = st.digging - && now > end - { - stop_digging(m, st); - } - // Sniffing. - if let Some(end) = st.sniffing_run - && now > end - { - st.sniffing_run = None; - if pose(m) == Pose::Sniffing { - set_pose(m, Pose::Standing); - } - st.sniffing = false; - if let Some(entity) = st.nearest_attackable.filter(|e| can_target(cx.w, *e)) - && let Some(p) = position_of(cx.w, entity) - { - if sniff_close(m, p) { - increase_anger(m, st, cx.w, Some(entity), DEFAULT_ANGER, true, cx.events); - } - if st.disturbance.is_none() { - let block = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; - set_disturbance(st, cx.w, now, block); - } - } - } - // Roar. - if let Some(end) = st.roaring { - if now > end { - st.roaring = None; - if pose(m) == Pose::Roaring { - set_pose(m, Pose::Standing); - } - if let Some(target) = st.roar_target.take() { - set_attack_target(st, target, now); - } - } else if !present(st.roar_sound_delay, now) && !present(st.roar_sound_cooldown, now) { - st.roar_sound_cooldown = st.expiry(now, ROAR_DURATION - ROAR_SOUND_DELAY); - sound(m, "entity.warden.roar", 3.0, 1.0, cx.events); - } - } - // Sonic boom. - if let Some(end) = st.sonic { - if now > end { - st.sonic = None; - st.sonic_cooldown = st.expiry(now, 40); - } else { - tick_sonic_boom(m, st, cx); - } - } - // The idle pause. - if let Some(pause) = st.pause - && now > pause.end - { - st.pause = None; - } -} -/// `Warden.closerThan(entity, 6, 20)` for the sniff. -fn sniff_close(m: &Mob, p: Vec3) -> bool { - closer_than(m, p, 6.0, 20.0) -} -fn tick_sonic_boom(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - let now = i64::from(m.age); - let Some(target) = st.attack_target else { +/// `SonicBoom.tick`: face the target; once the sound delay is over, the +/// beam, the sound, the damage and the knockback. +pub(super) fn tick_sonic_boom(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + let Some(target) = warden_brain::mem(m).attack_target.value() else { return; }; - if let Some(t) = cx.w.target_info(target) { + if let Some(t) = w.target_info(target) { m.look_at([t.position.x, t.position.y, t.position.z]); } - if present(st.sonic_sound_delay, now) || present(st.sonic_sound_cooldown, now) { + let mm = warden_brain::mem(m); + if mm.sonic_boom_sound_delay.present() || mm.sonic_boom_sound_cooldown.present() { return; } - st.sonic_sound_cooldown = st.expiry(now, SONIC_DURATION - SONIC_SOUND_DELAY); - if !can_target(cx.w, target) { + mm.sonic_boom_sound_cooldown.set_ttl((), 60 - 34); + if !can_target(w, target) { return; } - let Some(t) = cx.w.target_info(target) else { + let Some(t) = w.target_info(target) else { return; }; if !closer_than(m, t.position, 15.0, 20.0) { @@ -1218,14 +585,15 @@ fn tick_sonic_boom(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { let eye = [t.position.x, t.eye_y, t.position.z]; let delta = [eye[0] - source[0], eye[1] - source[1], eye[2] - source[2]]; let length = (delta[0] * delta[0] + delta[1] * delta[1] + delta[2] * delta[2]).sqrt(); - if length < 1.0e-9 { - return; - } - let normal = [delta[0] / length, delta[1] / length, delta[2] / length]; + let normal = if length < 1.0e-5 { + [0.0; 3] + } else { + [delta[0] / length, delta[1] / length, delta[2] / length] + }; let steps = length.floor() as i32 + 7; for i in 1..steps { let d = f64::from(i); - cx.events.push(MobEvent::Particles { + events.push(MobEvent::Particles { kind: "sonic_boom", at: [ source[0] + normal[0] * d, @@ -1235,17 +603,17 @@ fn tick_sonic_boom(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { count: 0, }); } - sound(m, "entity.warden.sonic_boom", 3.0, 1.0, cx.events); + sound(m, "entity.warden.sonic_boom", 3.0, 1.0, events); let from = at(m); // Players and the mobs hit here have no knockback resistance. let resistance = 0.0; match target { - Who::Player => cx.events.push(MobEvent::DamagePlayer { + Who::Player => events.push(MobEvent::DamagePlayer { amount: 10.0, from, kind: "minecraft:sonic_boom", }), - Who::Mob(id) => cx.events.push(MobEvent::AttackMob { + Who::Mob(id) => events.push(MobEvent::AttackMob { target: id, amount: 10.0, source: Damage { @@ -1257,7 +625,7 @@ fn tick_sonic_boom(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { } let horizontal = 2.5 * (1.0 - resistance); let vertical = 0.5 * (1.0 - resistance); - cx.events.push(MobEvent::Push { + events.push(MobEvent::Push { target, velocity: [ normal[0] * horizontal, @@ -1266,109 +634,9 @@ fn tick_sonic_boom(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { ], }); } - -// ---- walking: MoveToTargetSink ---- - -fn reached_target(m: &Mob, w: &MobWorld, walk: &Walk) -> bool { - track_block(w, walk.target).is_some_and(|p| manhattan(p, block_pos(m)) <= walk.close_enough) -} -/// `MoveToTargetSink.tryComputePath`. -fn try_compute_path(m: &mut Mob, st: &mut Warden, w: &MobWorld, walk: &Walk) -> Option { - let target = track_block(w, walk.target)?; - let now = i64::from(m.age); - let mut path = m.create_path_to(w, target, 0); - if reached_target(m, w, walk) { - st.cant_reach_since = None; - return None; - } - let can_reach = path.as_ref().is_some_and(|p| p.reached); - if can_reach { - st.cant_reach_since = None; - } else if st.cant_reach_since.is_none() { - st.cant_reach_since = Some(now); - } - if path.is_some() { - return path; - } - let bottom_center = [ - f64::from(target[0]) + 0.5, - f64::from(target[1]), - f64::from(target[2]) + 0.5, - ]; - if let Some(p) = m.land_random_pos_towards(w, 10, 7, bottom_center) { - path = m.create_path_to_entity(w, p, 0); - } - path -} -fn start_move_sink(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - let now = i64::from(m.age); - let Some(walk) = st.walk else { return }; - if st.move_sink.is_some() { - return; - } - if st.move_cooldown > 0 { - st.move_cooldown -= 1; - return; - } - let reached = reached_target(m, cx.w, &walk); - if !reached && let Some(path) = try_compute_path(m, st, cx.w, &walk) { - let duration = 150 + i64::from(m.random.next_int_bound(101).unwrap_or(0)); - let last = track_block(cx.w, walk.target).unwrap_or_default(); - m.nav_move_to_path(Some(path.clone()), f64::from(walk.speed)); - st.move_sink = Some(MoveSink { - end: now + duration, - last_target: last, - speed: walk.speed, - path: Some(path), - }); - return; - } - st.walk = None; - if reached { - st.cant_reach_since = None; - } -} -fn tick_move_sink(m: &mut Mob, st: &mut Warden, cx: &mut Cx) { - let now = i64::from(m.age); - let Some(mut sink) = st.move_sink.take() else { - return; - }; - let walk = st.walk; - let still = now <= sink.end - && walk.is_some_and(|walk| { - let spectator = matches!(walk.target, Track::Entity(Who::Player, _)) - && cx.w.player.as_ref().is_some_and(|p| p.spectator); - !m.ai.nav.is_done() && !reached_target(m, cx.w, &walk) && !spectator - }); - if !still { - // MoveToTargetSink.stop. - if let Some(walk) = walk - && !reached_target(m, cx.w, &walk) - && m.ai.nav.stuck - { - st.move_cooldown = m.random.next_int_bound(40).unwrap_or(0); - } - m.nav_stop(); - st.walk = None; - return; - } - if let Some(walk) = walk - && let Some(target) = track_block(cx.w, walk.target) - && dist_sqr(target, sink.last_target) > 4.0 - && let Some(path) = try_compute_path(m, st, cx.w, &walk) - { - sink.last_target = target; - sink.speed = walk.speed; - m.nav_move_to_path(Some(path.clone()), f64::from(walk.speed)); - sink.path = Some(path); - } - st.move_sink = Some(sink); -} - -// ---- per-tick client behaviour ---- - -/// `Warden.tick` on the client: the heartbeat, the tendrils and the digging -/// crumbs; the keyframe states follow the pose. +/// `Warden.tick` on the client: the heartbeat (pitched by the client's copy +/// of the warden: a level event sound here), the tendril and heart +/// animations, digging crumbs, and keyframes that ended. pub fn ai_step(m: &mut Mob, events: &mut Vec) { let Some(st) = m.extra.warden.as_ref() else { return; @@ -1377,8 +645,12 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { let delay = heart_beat_delay(client_anger); if i64::from(m.age) % i64::from(delay) == 0 { m.anim.v[HEART] = 10.0; - let pitch = voice_pitch(m); - sound(m, "entity.warden.heartbeat", 5.0, pitch, events); + events.push(MobEvent::LevelEventSound { + sound: "entity.warden.heartbeat", + at: at(m), + volume: 5.0, + spread: 0.2, + }); } // The animation values count down after the sync of the last tick. for slot in [TENDRIL, HEART] { @@ -1429,10 +701,11 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { } /// Test aid: the minute of calm ran out. pub fn expire_dig_cooldown(m: &mut Mob) { - if let Some(st) = m.extra.warden.as_mut() { - st.dig_cooldown = None; - st.attack_target = None; - st.roar_target = None; + if m.extra.warden.is_some() { + let mm = warden_brain::mem(m); + mm.dig_cooldown.clear(); + mm.attack_target.clear(); + mm.roar_target.clear(); } } /// The warden's state for the control socket. @@ -1444,17 +717,13 @@ pub fn describe(m: &Mob) -> Option { .iter() .map(|w| format!("{w:?}={}", st.anger.anger_of(*w))) .collect(); + let (activities, memories) = warden_brain::describe(m).unwrap_or_default(); Some(serde_json::json!({ "pose": format!("{:?}", pose(m)), - "activity": format!("{:?}", st.activity), + "activities": activities, + "memories": memories, "anger_level": format!("{:?}", anger_level(m)), "anger": anger, - "attack_target": st.attack_target.map(|t| format!("{t:?}")), - "roar_target": st.roar_target.map(|t| format!("{t:?}")), - "disturbance": st.disturbance.map(|(p, _)| p), - "walk": st.walk.is_some(), - "dig_cooldown": st.dig_cooldown.map(|t| t - i64::from(m.age)), - "sniff_cooldown": st.sniff_cooldown.map(|t| t - i64::from(m.age)), "vibration": st.vibration.current.map(|i| i.event), })) } diff --git a/crates/horizon-client/src/mobs/warden_brain.rs b/crates/horizon-client/src/mobs/warden_brain.rs new file mode 100644 index 000000000..a513bd6b7 --- /dev/null +++ b/crates/horizon-client/src/mobs/warden_brain.rs @@ -0,0 +1,1343 @@ +//! The warden's `Brain` (`Warden.BRAIN_PROVIDER` and `WardenAi`), ported +//! behaviour for behaviour on the villager brain's machinery (`Slot` +//! memories with their time to live, `Tracker`s, `WalkTarget`s and the +//! nearest-visible list): the two sensors and their scan phases, the core, +//! emerge, dig, idle, roar, fight, investigate and sniff activities, and their +//! behaviours started and ticked in vanilla's order (priority, then the +//! activity's slot in `Brain.availableBehaviorsByPriority`'s hash map, then +//! the order the activity lists them in). +//! +//! The level random (`ServerLevel.getRandom`) draws every `Behavior`'s +//! duration and the idle `DoNothing`, the sniff cooldown and the spot near a +//! disturbance; the warden's own random drives strolls, sounds and swimming. +//! `RunOne` shuffles with a random of its own, seeded with the brain's +//! shuffle seed. +use super::{ + Mob, MobEvent, MobWorld, Who, + goals::Cx, + path::Path, + villager_brain::{Slot, Tracker, Visible, WalkTarget}, + warden::{self, Pose}, +}; +use horizon_core::{ + geometry::Vec3, + random::{LegacyRandom, RandomSource}, +}; + +/// `WardenAi` timings. +pub const EMERGE_DURATION: i32 = 134; +pub const ROAR_DURATION: i32 = 84; +const SNIFFING_DURATION: i32 = 84; +const DIGGING_DURATION: i32 = 100; +pub const DIGGING_COOLDOWN: i64 = 1200; +const MELEE_ATTACK_COOLDOWN: i64 = 18; +const SONIC_DURATION: i32 = 60; +const SONIC_SOUND_DELAY: i64 = 34; +const ROAR_SOUND_DELAY: i64 = 25; +const DISTURBANCE_EXPIRY: i64 = 100; +/// `Warden.createAttributes`: the follow range the fight's look target uses. +const FOLLOW_RANGE: f64 = 24.0; + +/// `Activity`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Act { + Core, + Emerge, + Dig, + Idle, + Roar, + Fight, + Investigate, + Sniff, +} +impl Act { + pub fn name(self) -> &'static str { + match self { + Act::Core => "core", + Act::Emerge => "emerge", + Act::Dig => "dig", + Act::Idle => "idle", + Act::Roar => "roar", + Act::Fight => "fight", + Act::Investigate => "investigate", + Act::Sniff => "sniff", + } + } + /// The bucket of `HashMap` (16 buckets, the hash of the + /// name); roar and investigate share one but never a priority. + fn slot(self) -> u8 { + match self { + Act::Core => 1, + Act::Dig => 3, + Act::Idle => 5, + Act::Sniff => 6, + Act::Emerge => 10, + Act::Roar | Act::Investigate => 11, + Act::Fight => 14, + } + } + /// Its place in `getActivities` (insertion order inside a bucket). + fn order(self) -> u8 { + self as u8 + } +} + +/// The memories the warden's brain registers. +#[derive(Clone, Debug, Default)] +pub struct Memories { + pub nearest_players: Slot>, + pub nearest_visible_player: Slot, + pub nearest_visible_targetable_player: Slot, + pub nearest_visible_targetable_players: Slot>, + pub mobs: Slot>, + pub visible_mobs: Slot, + pub nearest_attackable: Slot, + pub look_target: Slot, + pub walk_target: Slot, + pub path: Slot, + pub cant_reach_walk_target_since: Slot, + pub attack_target: Slot, + pub attack_cooling_down: Slot, + pub roar_target: Slot, + pub disturbance_location: Slot<[i32; 3]>, + pub recent_projectile: Slot<()>, + pub is_sniffing: Slot<()>, + pub is_emerging: Slot<()>, + pub roar_sound_delay: Slot<()>, + pub dig_cooldown: Slot<()>, + pub roar_sound_cooldown: Slot<()>, + pub sniff_cooldown: Slot<()>, + pub touch_cooldown: Slot<()>, + pub vibration_cooldown: Slot<()>, + pub sonic_boom_cooldown: Slot<()>, + pub sonic_boom_sound_cooldown: Slot<()>, + pub sonic_boom_sound_delay: Slot<()>, +} +impl Memories { + fn tick(&mut self) { + self.nearest_players.tick(); + self.nearest_visible_player.tick(); + self.nearest_visible_targetable_player.tick(); + self.nearest_visible_targetable_players.tick(); + self.mobs.tick(); + self.visible_mobs.tick(); + self.nearest_attackable.tick(); + self.look_target.tick(); + self.walk_target.tick(); + self.path.tick(); + self.cant_reach_walk_target_since.tick(); + self.attack_target.tick(); + self.attack_cooling_down.tick(); + self.roar_target.tick(); + self.disturbance_location.tick(); + self.recent_projectile.tick(); + self.is_sniffing.tick(); + self.is_emerging.tick(); + self.roar_sound_delay.tick(); + self.dig_cooldown.tick(); + self.roar_sound_cooldown.tick(); + self.sniff_cooldown.tick(); + self.touch_cooldown.tick(); + self.vibration_cooldown.tick(); + self.sonic_boom_cooldown.tick(); + self.sonic_boom_sound_cooldown.tick(); + self.sonic_boom_sound_delay.tick(); + } +} + +/// `Behavior`'s bookkeeping: running, and until when. +#[derive(Clone, Debug)] +struct Timed { + running: bool, + end: i64, + min: i32, + max: i32, +} +impl Timed { + fn new(min: i32, max: i32) -> Self { + Self { + running: false, + end: 0, + min, + max, + } + } + /// `Behavior.tryStart`'s duration draw (made even when it cannot vary). + fn begin(&mut self, cx: &mut Bx) { + self.running = true; + let d = self.min + cx.lr.next_int_bound(self.max + 1 - self.min).unwrap_or(0); + self.end = cx.now + i64::from(d); + } +} + +/// `RunOne`'s `ShufflingList` over a stroll (weight 2) and `DoNothing` (1). +#[derive(Clone, Debug)] +struct Gate { + running: bool, + random: LegacyRandom, + kids: Vec<(B, i32, f64)>, +} + +/// One behaviour of the warden's activities. +#[derive(Clone, Debug)] +enum B { + Swim(Timed), + SetWardenLookTarget(bool), + LookAtTargetSink(Timed), + MoveToTargetSink { + t: Timed, + cooldown: i32, + path: Option, + last_target: Option<[i32; 3]>, + speed: f32, + }, + Emerging(Timed), + ForceUnmount(Timed), + Digging(Timed), + SetRoarTarget(bool), + TryToSniff(bool), + RunOne(Box), + Stroll(bool), + DoNothing(Timed), + GoToDisturbance(bool), + Sniffing(Timed), + Roar(Timed), + DigCooldownSetter(bool), + StopAttackingIfTargetInvalid(bool), + SetEntityLookTarget(bool), + SetWalkTargetFromAttackTarget(bool), + SonicBoom(Timed), + MeleeAttack(bool), +} + +#[derive(Clone, Debug)] +struct Entry { + act: Act, + b: B, +} + +/// The warden's brain. +#[derive(Clone, Debug)] +pub struct Brain { + pub mem: Memories, + /// `NEAREST_PLAYERS` and `WARDEN_ENTITY_SENSOR`: ticks to the next scan. + sensors: [i64; 2], + /// The active non-core activity (`CORE` is always active). + pub activity: Act, + list: Vec, + pub shuffle_seed: i64, +} +impl Default for Brain { + fn default() -> Self { + Self::new(0) + } +} +impl Brain { + pub fn new(shuffle_seed: i64) -> Self { + Self { + mem: Memories::default(), + sensors: [0; 2], + activity: Act::Idle, + list: activities(shuffle_seed), + shuffle_seed, + } + } + pub fn is_active(&self, a: Act) -> bool { + a == Act::Core || a == self.activity + } + fn requirements_met(&self, a: Act) -> bool { + let m = &self.mem; + match a { + Act::Emerge => m.is_emerging.present(), + Act::Dig => !m.roar_target.present() && !m.dig_cooldown.present(), + Act::Roar => m.roar_target.present(), + Act::Fight => m.attack_target.present(), + Act::Investigate => m.disturbance_location.present(), + Act::Sniff => m.is_sniffing.present(), + Act::Core | Act::Idle => true, + } + } + /// `setActiveActivity`: leaving an activity erases the memory it needed. + fn set_active(&mut self, a: Act) { + if self.is_active(a) { + return; + } + let m = &mut self.mem; + match self.activity { + Act::Emerge => m.is_emerging.clear(), + Act::Roar => m.roar_target.clear(), + Act::Fight => m.attack_target.clear(), + Act::Investigate => m.disturbance_location.clear(), + Act::Sniff => m.is_sniffing.clear(), + Act::Core | Act::Dig | Act::Idle => {} + } + self.activity = a; + } + /// `WardenAi.updateActivity`: `setActiveActivityToFirstValid`. + pub fn update_activity(&mut self) { + for a in [ + Act::Emerge, + Act::Dig, + Act::Roar, + Act::Fight, + Act::Investigate, + Act::Sniff, + Act::Idle, + ] { + if self.requirements_met(a) { + self.set_active(a); + break; + } + } + } + /// `Sensor.randomlyDelayStart` for both sensors, from the warden's random. + pub fn delay_sensors(&mut self, random: &mut LegacyRandom) { + for s in &mut self.sensors { + *s = i64::from(random.next_int_bound(20).unwrap_or(0)); + } + } +} + +/// `WardenAi.getActivities`, in the order `Brain.startEachNonRunningBehavior` +/// meets the behaviours. +fn activities(seed: i64) -> Vec { + let gate = Gate { + running: false, + random: LegacyRandom::new(seed), + kids: vec![ + (B::Stroll(false), 2, 0.0), + (B::DoNothing(Timed::new(30, 60)), 1, 0.0), + ], + }; + let mut list = vec![ + (0, Act::Core, B::Swim(Timed::new(60, 60))), + (1, Act::Core, B::SetWardenLookTarget(false)), + (2, Act::Core, B::LookAtTargetSink(Timed::new(45, 90))), + ( + 3, + Act::Core, + B::MoveToTargetSink { + t: Timed::new(150, 250), + cooldown: 0, + path: None, + last_target: None, + speed: 0.0, + }, + ), + (5, Act::Emerge, B::Emerging(Timed::new(EMERGE_DURATION, EMERGE_DURATION))), + (0, Act::Dig, B::ForceUnmount(Timed::new(60, 60))), + (1, Act::Dig, B::Digging(Timed::new(DIGGING_DURATION, DIGGING_DURATION))), + (10, Act::Idle, B::SetRoarTarget(false)), + (11, Act::Idle, B::TryToSniff(false)), + (12, Act::Idle, B::RunOne(Box::new(gate))), + (10, Act::Roar, B::Roar(Timed::new(ROAR_DURATION, ROAR_DURATION))), + (10, Act::Fight, B::DigCooldownSetter(false)), + (11, Act::Fight, B::StopAttackingIfTargetInvalid(false)), + (12, Act::Fight, B::SetEntityLookTarget(false)), + (13, Act::Fight, B::SetWalkTargetFromAttackTarget(false)), + (14, Act::Fight, B::SonicBoom(Timed::new(SONIC_DURATION, SONIC_DURATION))), + (15, Act::Fight, B::MeleeAttack(false)), + (5, Act::Investigate, B::SetRoarTarget(false)), + (6, Act::Investigate, B::GoToDisturbance(false)), + (5, Act::Sniff, B::SetRoarTarget(false)), + (6, Act::Sniff, B::Sniffing(Timed::new(SNIFFING_DURATION, SNIFFING_DURATION))), + ]; + // A stable sort keeps each activity's own order. + list.sort_by_key(|(prio, act, _)| (*prio, act.slot(), act.order())); + list.into_iter() + .map(|(_, act, b)| Entry { act, b }) + .collect() +} + +/// What behaviours read and emit during a brain tick. +pub struct Bx<'a, 'w> { + pub w: &'a MobWorld<'w>, + pub lr: &'a mut LegacyRandom, + pub events: &'a mut Vec, + pub now: i64, +} + +fn brain(m: &Mob) -> Option<&Brain> { + m.extra.warden.as_ref().map(|w| &w.brain) +} +pub(super) fn mem(m: &mut Mob) -> &mut Memories { + &mut m.extra.warden.as_mut().expect("a warden").brain.mem +} +pub(super) fn mem_ref(m: &Mob) -> Option<&Memories> { + brain(m).map(|b| &b.mem) +} + +/// `Brain.tick` (from `Warden.customServerAiStep`). +pub fn tick(m: &mut Mob, w: &MobWorld, lr: &mut LegacyRandom, events: &mut Vec) { + if m.extra.warden.is_none() { + return; + } + // forgetOutdatedMemories + mem(m).tick(); + tick_sensors(m, w); + let Some(st) = m.extra.warden.as_mut() else { + return; + }; + let mut list = std::mem::take(&mut st.brain.list); + let mut cx = Bx { + w, + lr, + events, + now: w.game_time, + }; + for e in &mut list { + let active = m + .extra + .warden + .as_ref() + .is_some_and(|st| st.brain.is_active(e.act)); + if active && !e.b.running() { + e.b.try_start(m, &mut cx); + } + } + for e in &mut list { + if e.b.running() { + e.b.tick_or_stop(m, &mut cx); + } + } + if let Some(st) = m.extra.warden.as_mut() { + st.brain.list = list; + } +} + +// ---- Sensors ------------------------------------------------------------ + +fn tick_sensors(m: &mut Mob, w: &MobWorld) { + for i in 0..2 { + let fire = { + let b = &mut m.extra.warden.as_mut().expect("a warden").brain; + b.sensors[i] -= 1; + if b.sensors[i] <= 0 { + b.sensors[i] = 20; + true + } else { + false + } + }; + if fire { + if i == 0 { + sense_players(m, w); + } else { + sense_entities(m, w); + } + } + } +} +/// `TargetingConditions.forNonCombat().range(followRange)` (sensors use the +/// follow range of the mob that scanned last). +fn targetable(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + let range = m.attrs.follow_range; + match who { + Who::Player => m.can_see_player(w, range), + Who::Mob(id) => { + let Some(s) = w.seen(id) else { return false }; + s.alive && m.distance_sqr(s.position) <= range.max(2.0).powi(2) && m.sees(w, who) + } + } +} +/// `PlayerSensor`. +fn sense_players(m: &mut Mob, w: &MobWorld) { + let range = m.attrs.follow_range; + let near = w + .player + .as_ref() + .is_some_and(|p| !p.spectator && m.distance_sqr(p.position) < range * range); + let players: Vec = if near { vec![Who::Player] } else { vec![] }; + let visible: Vec = players + .iter() + .copied() + .filter(|&p| targetable(m, w, p)) + .collect(); + let attackable: Vec = visible + .iter() + .copied() + .filter(|_| m.can_target_player(w, range, true)) + .collect(); + let mm = mem(m); + mm.nearest_players.set_list(players); + mm.nearest_visible_player.set_opt(visible.first().copied()); + mm.nearest_visible_targetable_players + .set_list(attackable.clone()); + mm.nearest_visible_targetable_player + .set_opt(attackable.first().copied()); +} +/// `WardenEntitySensor`: `NearestLivingEntitySensor`, then the nearest +/// targetable player, else the nearest other targetable entity. +fn sense_entities(m: &mut Mob, w: &MobWorld) { + let r = m.attrs.follow_range; + let area = m.bounds().inflate(Vec3::new(r, r, r)); + let mut found: Vec<(Who, f64)> = Vec::new(); + for o in w.others { + if o.id != m.id && o.alive && o.bounds.intersects(area) { + found.push((Who::Mob(o.id), m.distance_sqr(o.position))); + } + } + if let Some(p) = &w.player + && p.alive + && p.bounds.intersects(area) + { + found.push((Who::Player, m.distance_sqr(p.position))); + } + found.sort_by(|a, b| a.1.total_cmp(&b.1)); + let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let attackable = list + .iter() + .copied() + .find(|&e| e == Who::Player && warden::can_target(w, e)) + .or_else(|| { + list.iter() + .copied() + .find(|&e| e != Who::Player && warden::can_target(w, e)) + }); + let mm = mem(m); + mm.mobs.set_list(list.clone()); + mm.visible_mobs.set(Visible { + list, + cache: Vec::new(), + }); + mm.nearest_attackable.set_opt(attackable); +} +/// The visible-entities memory's line-of-sight test, cached per memory. +fn visible_test(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + match mem_ref(m).and_then(|mm| mm.visible_mobs.get()) { + Some(v) => { + if let Some(&(_, r)) = v.cache.iter().find(|(k, _)| *k == who) { + return r; + } + } + None => return false, + } + // Sensor.isEntityTargetable: the attack target ignores invisibility. + let r = targetable(m, w, who); + if let Some(v) = mem(m).visible_mobs.get_mut() { + v.cache.push((who, r)); + } + r +} +/// `NearestVisibleLivingEntities.contains(entity)`. +fn visible_contains(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + let listed = mem_ref(m) + .and_then(|mm| mm.visible_mobs.get()) + .is_some_and(|v| v.list.contains(&who)); + listed && visible_test(m, w, who) +} +/// `NearestVisibleLivingEntities.findClosest`. +fn find_closest(m: &mut Mob, w: &MobWorld, filter: impl Fn(&Mob, Who) -> bool) -> Option { + let list = mem_ref(m)?.visible_mobs.get()?.list.clone(); + list.into_iter() + .find(|&who| filter(m, who) && visible_test(m, w, who)) +} + +// ---- Shared warden actions ------------------------------------------------ + +fn block_of(p: Vec3) -> [i32; 3] { + [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] +} +fn manhattan(a: [i32; 3], b: [i32; 3]) -> i32 { + (a[0] - b[0]).abs() + (a[1] - b[1]).abs() + (a[2] - b[2]).abs() +} +fn dist_sqr(a: [i32; 3], b: [i32; 3]) -> i64 { + (0..3).map(|i| i64::from(a[i] - b[i]).pow(2)).sum() +} +/// `WardenAi.setDigCooldown`. +pub(super) fn set_dig_cooldown(m: &mut Mob) { + let mm = mem(m); + if mm.dig_cooldown.present() { + mm.dig_cooldown.set_ttl((), DIGGING_COOLDOWN); + } +} +/// `WardenAi.setDisturbanceLocation`. +pub(super) fn set_disturbance(m: &mut Mob, w: &MobWorld, position: [i32; 3]) { + if warden::entity_angry_at(m, w).is_some() || mem(m).attack_target.present() { + return; + } + set_dig_cooldown(m); + let mm = mem(m); + mm.sniff_cooldown.set_ttl((), DISTURBANCE_EXPIRY); + mm.look_target + .set_ttl(Tracker::Block(position), DISTURBANCE_EXPIRY); + mm.disturbance_location.set_ttl(position, DISTURBANCE_EXPIRY); + mm.walk_target.clear(); +} +/// `Warden.setAttackTarget`. +pub(super) fn set_attack_target(m: &mut Mob, target: Who) { + let mm = mem(m); + mm.roar_target.clear(); + mm.attack_target.set(target); + mm.cant_reach_walk_target_since.clear(); + mm.sonic_boom_cooldown.set_ttl((), 200); +} +/// `Entity.closerThan(target, horizontal, vertical)`. +fn closer_than(m: &Mob, p: Vec3, horizontal: f64, vertical: f64) -> bool { + let (dx, dy, dz) = (p.x - m.position.x, p.y - m.position.y, p.z - m.position.z); + dx * dx + dz * dz < horizontal * horizontal && dy * dy < vertical * vertical +} +/// `PositionTracker.isVisibleBy`. +fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { + match t { + Tracker::Entity(who, _) => { + w.target_info(who).is_some_and(|i| i.alive) && visible_contains(m, w, who) + } + _ => true, + } +} +/// `MoveToTargetSink.reachedTarget`. +fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { + walk.target + .block(w) + .is_some_and(|p| manhattan(p, block_of(m.position)) <= walk.close) +} +/// `MoveToTargetSink.tryComputePath`. +fn compute_path( + m: &mut Mob, + cx: &mut Bx, + walk: &WalkTarget, + path: &mut Option, + speed: &mut f32, +) -> bool { + let Some(target) = walk.target.block(cx.w) else { + return false; + }; + *path = m.create_path_to(cx.w, target, 0); + *speed = walk.speed; + if reached(m, cx.w, walk) { + mem(m).cant_reach_walk_target_since.clear(); + } else { + let can_reach = path.as_ref().is_some_and(|p| p.reached); + let mm = mem(m); + if can_reach { + mm.cant_reach_walk_target_since.clear(); + } else if !mm.cant_reach_walk_target_since.present() { + mm.cant_reach_walk_target_since.set(cx.now); + } + if path.is_some() { + return true; + } + let to = [ + f64::from(target[0]) + 0.5, + f64::from(target[1]), + f64::from(target[2]) + 0.5, + ]; + if let Some(step) = + m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) + { + let p = [ + step[0].floor() as i32, + step[1].floor() as i32, + step[2].floor() as i32, + ]; + *path = m.create_path_to(cx.w, p, 0); + return path.is_some(); + } + } + false +} +fn same_path(a: Option<&Path>, b: Option<&Path>) -> bool { + match (a, b) { + (None, None) => true, + (Some(a), Some(b)) => a.nodes == b.nodes && a.target == b.target, + _ => false, + } +} +fn sound(m: &Mob, name: &'static str, volume: f32, pitch: f32, events: &mut Vec) { + events.push(MobEvent::Sound( + name, + [m.position.x, m.position.y, m.position.z], + volume, + pitch, + )); +} + +// ---- Behaviours ----------------------------------------------------------- + +impl B { + fn running(&self) -> bool { + match self { + B::Swim(t) + | B::LookAtTargetSink(t) + | B::Emerging(t) + | B::ForceUnmount(t) + | B::Digging(t) + | B::DoNothing(t) + | B::Sniffing(t) + | B::Roar(t) + | B::SonicBoom(t) => t.running, + B::MoveToTargetSink { t, .. } => t.running, + B::RunOne(g) => g.running, + B::SetWardenLookTarget(r) + | B::SetRoarTarget(r) + | B::TryToSniff(r) + | B::Stroll(r) + | B::GoToDisturbance(r) + | B::DigCooldownSetter(r) + | B::StopAttackingIfTargetInvalid(r) + | B::SetEntityLookTarget(r) + | B::SetWalkTargetFromAttackTarget(r) + | B::MeleeAttack(r) => *r, + } + } + + /// `BehaviorControl.tryStart`. + fn try_start(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + match self { + B::Swim(t) => { + if !swim_condition(m) { + return false; + } + t.begin(cx); + true + } + B::SetWardenLookTarget(r) => one(r, || { + let mm = mem(m); + if mm.attack_target.present() { + return false; + } + let target = mm + .roar_target + .value() + .and_then(|who| cx.w.target_info(who)) + .map(|t| block_of(t.position)) + .or_else(|| mm.disturbance_location.value()); + let Some(p) = target else { return false }; + mem(m).look_target.set(Tracker::Block(p)); + true + }), + B::LookAtTargetSink(t) => { + if !mem(m).look_target.present() { + return false; + } + t.begin(cx); + true + } + B::MoveToTargetSink { + t, + cooldown, + path, + last_target, + speed, + } => { + let mm = mem(m); + if mm.path.present() || !mm.walk_target.present() { + return false; + } + // checkExtraStartConditions + if *cooldown > 0 { + *cooldown -= 1; + return false; + } + let Some(walk) = mm.walk_target.value() else { + return false; + }; + let reached = reached(m, cx.w, &walk); + if !reached && compute_path(m, cx, &walk, path, speed) { + *last_target = walk.target.block(cx.w); + t.begin(cx); + // start + mem(m).path.set_opt(path.clone()); + m.nav_move_to_path(path.clone(), f64::from(*speed)); + return true; + } + let mm = mem(m); + mm.walk_target.clear(); + if reached { + mm.cant_reach_walk_target_since.clear(); + } + false + } + B::Emerging(t) => { + let mm = mem(m); + if !mm.is_emerging.present() || mm.walk_target.present() { + return false; + } + t.begin(cx); + warden::set_pose(m, Pose::Emerging); + sound(m, "entity.warden.emerge", 5.0, 1.0, cx.events); + true + } + // ForceUnmount: a warden never rides (Warden.canRide). + B::ForceUnmount(_) => false, + B::Digging(t) => { + let mm = mem(m); + if mm.attack_target.present() || mm.walk_target.present() { + return false; + } + let liquid = m.fluids.in_water || m.fluids.in_lava; + if !(m.on_ground || liquid) { + return false; + } + t.begin(cx); + if m.on_ground { + warden::set_pose(m, Pose::Digging); + sound(m, "entity.warden.dig", 5.0, 1.0, cx.events); + } else { + sound(m, "entity.warden.agitated", 5.0, 1.0, cx.events); + // `stop` without `doStop`: discarded, still running. + m.removed = true; + } + true + } + B::SetRoarTarget(r) => one(r, || { + let mm = mem(m); + if mm.roar_target.present() || mm.attack_target.present() { + return false; + } + let Some(target) = warden::entity_angry_at(m, cx.w) else { + return false; + }; + if !warden::can_target(cx.w, target) { + return false; + } + let mm = mem(m); + mm.roar_target.set(target); + mm.cant_reach_walk_target_since.clear(); + true + }), + B::TryToSniff(r) => one(r, || { + let mm = mem(m); + if mm.sniff_cooldown.present() + || !mm.nearest_attackable.present() + || mm.disturbance_location.present() + { + return false; + } + mm.is_sniffing.set(()); + // UniformInt.of(100, 200).sample(level.getRandom()) + let cooldown = 100 + cx.lr.next_int_bound(101).unwrap_or(0); + let mm = mem(m); + mm.sniff_cooldown.set_ttl((), i64::from(cooldown)); + mm.walk_target.clear(); + warden::set_pose(m, Pose::Sniffing); + true + }), + B::RunOne(g) => { + if mem(m).is_sniffing.present() { + return false; + } + g.running = true; + // ShufflingList.shuffle: a fresh weight for each entry in the + // current order, then a stable sort. + for k in &mut g.kids { + let r = g.random.next_float(); + k.2 = -f64::from(r).powf(f64::from(1.0_f32 / k.1 as f32)); + } + g.kids.sort_by(|a, b| a.2.total_cmp(&b.2)); + for k in &mut g.kids { + if !k.0.running() && k.0.try_start(m, cx) { + break; + } + } + true + } + B::Stroll(r) => one(r, || { + if mem(m).walk_target.present() { + return false; + } + // RandomStroll.stroll(0.5): LandRandomPos.getPos(body, 10, 7). + let target = m.land_random_pos(cx.w, 10, 7); + mem(m).walk_target.set_opt(target.map(|p| WalkTarget { + target: Tracker::Block([ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ]), + speed: 0.5, + close: 0, + })); + true + }), + B::DoNothing(t) => { + t.begin(cx); + true + } + B::GoToDisturbance(r) => one(r, || { + let mm = mem(m); + if mm.attack_target.present() || mm.walk_target.present() { + return false; + } + let Some(p) = mm.disturbance_location.value() else { + return false; + }; + // Vec3i.closerThan(body.blockPosition(), 2) + if dist_sqr(p, block_of(m.position)) >= 4 { + // GoToTargetLocation.getNearbyPos: the level random. + let dx = cx.lr.next_int_bound(3).unwrap_or(0) - 1; + let dz = cx.lr.next_int_bound(3).unwrap_or(0) - 1; + let near = [p[0] + dx, p[1], p[2] + dz]; + let mm = mem(m); + mm.look_target.set(Tracker::Block(near)); + mm.walk_target.set(WalkTarget { + target: Tracker::Block(near), + speed: 0.7, + close: 2, + }); + } + true + }), + B::Sniffing(t) => { + let mm = mem(m); + if !mm.is_sniffing.present() + || mm.attack_target.present() + || mm.walk_target.present() + { + return false; + } + t.begin(cx); + sound(m, "entity.warden.sniff", 5.0, 1.0, cx.events); + true + } + B::Roar(t) => { + let mm = mem(m); + if mm.attack_target.present() { + return false; + } + let Some(target) = mm.roar_target.value() else { + return false; + }; + t.begin(cx); + let mm = mem(m); + mm.roar_sound_delay.set_ttl((), ROAR_SOUND_DELAY); + mm.walk_target.clear(); + // BehaviorUtils.lookAtEntity + mm.look_target.set(Tracker::Entity(target, true)); + warden::set_pose(m, Pose::Roaring); + warden::increase_anger(m, cx.w, Some(target), 20, false, cx.events); + true + } + B::DigCooldownSetter(r) => one(r, || { + set_dig_cooldown(m); + true + }), + B::StopAttackingIfTargetInvalid(r) => one(r, || { + let Some(target) = mem(m).attack_target.value() else { + return false; + }; + let alive = cx.w.target_info(target).is_some_and(|t| t.alive); + let can = warden::can_target(cx.w, target); + let angry = warden::anger_level(m).is_angry(); + if can && alive && angry { + return true; + } + // WardenAi.onTargetInvalid + if !can && let Some(st) = m.extra.warden.as_mut() { + st.anger.clear(target); + } + set_dig_cooldown(m); + mem(m).attack_target.clear(); + true + }), + B::SetEntityLookTarget(r) => one(r, || { + let mm = mem(m); + if mm.look_target.present() || !mm.visible_mobs.present() { + return false; + } + let target = mm.attack_target.value(); + let max = (FOLLOW_RANGE as f32 * FOLLOW_RANGE as f32) as f64; + let w = cx.w; + let found = find_closest(m, w, |m, who| { + Some(who) == target + && w.target_info(who) + .is_some_and(|t| m.distance_sqr(t.position) <= max) + }); + let Some(found) = found else { return false }; + mem(m).look_target.set(Tracker::Entity(found, true)); + true + }), + B::SetWalkTargetFromAttackTarget(r) => one(r, || { + let Some(target) = mem(m).attack_target.value() else { + return false; + }; + let w = cx.w; + let in_reach = mem(m).visible_mobs.present() + && visible_contains(m, w, target) + && w.target_info(target) + .is_some_and(|t| m.within_melee_range(&t)); + let mm = mem(m); + if in_reach { + mm.walk_target.clear(); + } else { + mm.look_target.set(Tracker::Entity(target, true)); + mm.walk_target.set(WalkTarget { + target: Tracker::Entity(target, false), + speed: 1.2, + close: 0, + }); + } + true + }), + B::SonicBoom(t) => { + let mm = mem(m); + if mm.sonic_boom_cooldown.present() { + return false; + } + let Some(target) = mm.attack_target.value() else { + return false; + }; + let close = cx + .w + .target_info(target) + .is_some_and(|i| closer_than(m, i.position, 15.0, 20.0)); + if !close { + return false; + } + t.begin(cx); + let mm = mem(m); + mm.attack_cooling_down + .set_ttl(true, i64::from(SONIC_DURATION)); + mm.sonic_boom_sound_delay.set_ttl((), SONIC_SOUND_DELAY); + // Entity event 62: the sonic boom keyframes start. + m.anim.states[warden::SONIC_BOOM].start(m.age as f32); + sound(m, "entity.warden.sonic_charge", 3.0, 1.0, cx.events); + true + } + B::MeleeAttack(r) => one(r, || { + let mm = mem(m); + if mm.attack_cooling_down.present() || !mm.visible_mobs.present() { + return false; + } + let Some(target) = mm.attack_target.value() else { + return false; + }; + let w = cx.w; + let Some(info) = w.target_info(target) else { + return false; + }; + if !(m.within_melee_range(&info) && visible_contains(m, w, target)) { + return false; + } + mem(m).look_target.set(Tracker::Entity(target, true)); + m.swing(); + warden::do_hurt_target(m, target, w, cx.events); + mem(m) + .attack_cooling_down + .set_ttl(true, MELEE_ATTACK_COOLDOWN); + true + }), + } + } + + /// `BehaviorControl.tickOrStop`. + fn tick_or_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + let now = cx.now; + match self { + B::Swim(t) => { + if now > t.end || !swim_condition(m) { + self.do_stop(m, cx); + } else if m.random.next_float() < 0.8 { + m.ai.jumping = true; + } + } + B::LookAtTargetSink(t) => { + let target = mem(m).look_target.value(); + let visible = match target { + Some(tr) => tracker_visible(m, cx.w, tr), + None => false, + }; + if now > t.end || !visible { + self.do_stop(m, cx); + } else if let Some(at) = target.and_then(|tr| tr.position(cx.w)) { + m.look_at(at); + } + } + B::MoveToTargetSink { + t, + path, + last_target, + speed, + .. + } => { + let still = path.is_some() + && last_target.is_some() + && mem(m).walk_target.value().is_some_and(|walk| { + !m.ai.nav.is_done() + && !reached(m, cx.w, &walk) + && !matches!(walk.target, Tracker::Entity(Who::Player, _) + if cx.w.player.as_ref().is_some_and(|p| p.spectator)) + }); + if now > t.end || !still { + self.do_stop(m, cx); + return; + } + let new_path = m.ai.nav.path.clone(); + if !same_path(path.as_ref(), new_path.as_ref()) { + *path = new_path.clone(); + mem(m).path.set_opt(new_path.clone()); + } + if new_path.is_some() + && let Some(last) = *last_target + && let Some(walk) = mem(m).walk_target.value() + && let Some(now_target) = walk.target.block(cx.w) + && dist_sqr(now_target, last) > 4 + && compute_path(m, cx, &walk, path, speed) + { + *last_target = Some(now_target); + mem(m).path.set_opt(path.clone()); + m.nav_move_to_path(path.clone(), f64::from(*speed)); + } + } + // canStillUse is true: they run their duration. + B::Emerging(t) | B::Sniffing(t) => { + if now > t.end { + self.do_stop(m, cx); + } + } + B::ForceUnmount(t) => { + if now > t.end { + self.do_stop(m, cx); + } + } + B::Digging(t) => { + if now > t.end || m.removed { + self.do_stop(m, cx); + } + } + B::DoNothing(t) => { + if now > t.end { + self.do_stop(m, cx); + } + } + B::RunOne(g) => { + for k in &mut g.kids { + if k.0.running() { + k.0.tick_or_stop(m, cx); + } + } + if !g.kids.iter().any(|k| k.0.running()) { + self.do_stop(m, cx); + } + } + B::Roar(t) => { + if now > t.end { + self.do_stop(m, cx); + return; + } + let mm = mem(m); + if !mm.roar_sound_delay.present() && !mm.roar_sound_cooldown.present() { + mm.roar_sound_cooldown + .set_ttl((), i64::from(ROAR_DURATION) - ROAR_SOUND_DELAY); + sound(m, "entity.warden.roar", 3.0, 1.0, cx.events); + } + } + B::SonicBoom(t) => { + if now > t.end { + self.do_stop(m, cx); + return; + } + warden::tick_sonic_boom(m, cx.w, cx.events); + } + // OneShot.tickOrStop: they stop the tick they ran. + _ => self.do_stop(m, cx), + } + } + + /// `BehaviorControl.doStop`. + fn do_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + match self { + B::Swim(t) | B::ForceUnmount(t) | B::DoNothing(t) => t.running = false, + B::LookAtTargetSink(t) => { + t.running = false; + mem(m).look_target.clear(); + } + B::MoveToTargetSink { + t, cooldown, path, .. + } => { + t.running = false; + if let Some(walk) = mem(m).walk_target.value() + && !reached(m, cx.w, &walk) + && m.ai.nav.stuck + { + *cooldown = cx.lr.next_int_bound(40).unwrap_or(0); + } + m.nav_stop(); + let mm = mem(m); + mm.walk_target.clear(); + mm.path.clear(); + *path = None; + } + B::Emerging(t) => { + t.running = false; + if warden::pose(m) == Pose::Emerging { + warden::set_pose(m, Pose::Standing); + } + } + B::Digging(t) => { + t.running = false; + m.removed = true; + } + B::RunOne(g) => { + g.running = false; + for k in &mut g.kids { + if k.0.running() { + k.0.do_stop(m, cx); + } + } + } + B::Sniffing(t) => { + t.running = false; + if warden::pose(m) == Pose::Sniffing { + warden::set_pose(m, Pose::Standing); + } + mem(m).is_sniffing.clear(); + let w = cx.w; + if let Some(entity) = mem(m).nearest_attackable.value() + && warden::can_target(w, entity) + && let Some(info) = w.target_info(entity) + { + if closer_than(m, info.position, 6.0, 20.0) { + warden::increase_anger(m, w, Some(entity), 35, true, cx.events); + } + if !mem(m).disturbance_location.present() { + set_disturbance(m, w, block_of(info.position)); + } + } + } + B::Roar(t) => { + t.running = false; + if warden::pose(m) == Pose::Roaring { + warden::set_pose(m, Pose::Standing); + } + if let Some(target) = mem(m).roar_target.value() { + set_attack_target(m, target); + } + mem(m).roar_target.clear(); + } + B::SonicBoom(t) => { + t.running = false; + mem(m).sonic_boom_cooldown.set_ttl((), 40); + } + B::SetWardenLookTarget(r) + | B::SetRoarTarget(r) + | B::TryToSniff(r) + | B::Stroll(r) + | B::GoToDisturbance(r) + | B::DigCooldownSetter(r) + | B::StopAttackingIfTargetInvalid(r) + | B::SetEntityLookTarget(r) + | B::SetWalkTargetFromAttackTarget(r) + | B::MeleeAttack(r) => *r = false, + } + } +} + +/// `OneShot.tryStart`: running when the trigger fires. +fn one(running: &mut bool, f: impl FnOnce() -> bool) -> bool { + if f() { + *running = true; + true + } else { + false + } +} +/// `Swim`: deeper than the jump threshold, or in lava. +fn swim_condition(m: &Mob) -> bool { + m.fluids.water > m.fluid_jump_threshold() || m.fluids.in_lava +} +/// The `Cx` the mob library's attacks take. +pub(super) fn cx<'a, 'w>(w: &'a MobWorld<'w>, events: &'a mut Vec) -> Cx<'a, 'w> { + Cx { w, events } +} + +// ---- Printing --------------------------------------------------------------- + +fn who(w: Who) -> String { + match w { + Who::Player => "player".into(), + Who::Mob(id) => format!("e{id}"), + } +} +fn pos(p: [i32; 3]) -> String { + format!("{},{},{}", p[0], p[1], p[2]) +} +fn tracker(t: Tracker) -> String { + match t { + Tracker::Entity(e, _) => who(e), + Tracker::Block(p) => pos(p), + Tracker::Point(v) => pos([ + v[0].floor() as i32, + v[1].floor() as i32, + v[2].floor() as i32, + ]), + } +} +/// The active activities and the memories with values, as the mob AI oracle +/// prints them (`act core|idle`, `mem name=value...` sorted). +pub fn describe(m: &Mob) -> Option<(String, String)> { + let b = brain(m)?; + let mut acts = ["core", b.activity.name()]; + acts.sort_unstable(); + let mm = &b.mem; + let mut out: Vec = Vec::new(); + let mut put = |name: &str, value: String, ttl: i64| { + if ttl == i64::MAX { + out.push(format!("{name}={value}")); + } else { + out.push(format!("{name}={value}@{ttl}")); + } + }; + macro_rules! slot { + ($name:expr, $s:expr, $f:expr) => { + if let Some(v) = $s.get() { + put($name, $f(v), $s.ttl()); + } + }; + } + let unit = |_: &()| "u".to_string(); + let list = |l: &Vec| format!("n{}", l.len()); + slot!("nearest_players", mm.nearest_players, list); + slot!("nearest_visible_player", mm.nearest_visible_player, |e: &Who| who(*e)); + slot!( + "nearest_visible_targetable_player", + mm.nearest_visible_targetable_player, + |e: &Who| who(*e) + ); + slot!( + "nearest_visible_targetable_players", + mm.nearest_visible_targetable_players, + list + ); + slot!("mobs", mm.mobs, list); + slot!("visible_mobs", mm.visible_mobs, |_: &Visible| { + "NearestVisibleLivingEntities".to_string() + }); + slot!("nearest_attackable", mm.nearest_attackable, |e: &Who| who(*e)); + slot!("look_target", mm.look_target, |t: &Tracker| tracker(*t)); + slot!("walk_target", mm.walk_target, |t: &WalkTarget| format!( + "{}/{:x}/{}", + tracker(t.target), + t.speed.to_bits(), + t.close + )); + slot!("path", mm.path, |p: &Path| format!("path{}", pos(p.target))); + slot!( + "cant_reach_walk_target_since", + mm.cant_reach_walk_target_since, + |t: &i64| t.to_string() + ); + slot!("attack_target", mm.attack_target, |e: &Who| who(*e)); + slot!("attack_cooling_down", mm.attack_cooling_down, |t: &bool| t + .to_string()); + slot!("roar_target", mm.roar_target, |e: &Who| who(*e)); + slot!( + "disturbance_location", + mm.disturbance_location, + |p: &[i32; 3]| pos(*p) + ); + slot!("recent_projectile", mm.recent_projectile, unit); + slot!("is_sniffing", mm.is_sniffing, unit); + slot!("is_emerging", mm.is_emerging, unit); + slot!("roar_sound_delay", mm.roar_sound_delay, unit); + slot!("dig_cooldown", mm.dig_cooldown, unit); + slot!("roar_sound_cooldown", mm.roar_sound_cooldown, unit); + slot!("sniff_cooldown", mm.sniff_cooldown, unit); + slot!("touch_cooldown", mm.touch_cooldown, unit); + slot!("vibration_cooldown", mm.vibration_cooldown, unit); + slot!("sonic_boom_cooldown", mm.sonic_boom_cooldown, unit); + slot!("sonic_boom_sound_cooldown", mm.sonic_boom_sound_cooldown, unit); + slot!("sonic_boom_sound_delay", mm.sonic_boom_sound_delay, unit); + out.sort(); + Some((acts.join("|"), out.join(" "))) +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java index 7185ec400..d44b4135e 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -467,6 +467,17 @@ public final class VanillaMobAiOracle { for (String flag : spec.flags) { if (flag.equals("persistent")) mob.setPersistenceRequired(); else if (flag.equals("noai")) mob.setNoAi(true); + // Warden.finalizeSpawn's own part (Mob.finalizeSpawn draws the level random, + // which is not seeded yet): a minute before digging, or climbing out first. + else if (flag.equals("digcooldown") || flag.equals("emerge")) { + mob.getBrain().setMemoryWithExpiry(net.minecraft.world.entity.ai.memory.MemoryModuleType.DIG_COOLDOWN, + net.minecraft.util.Unit.INSTANCE, 1200L); + if (flag.equals("emerge")) { + mob.setPose(net.minecraft.world.entity.Pose.EMERGING); + mob.getBrain().setMemoryWithExpiry(net.minecraft.world.entity.ai.memory.MemoryModuleType.IS_EMERGING, + net.minecraft.util.Unit.INSTANCE, net.minecraft.world.entity.monster.warden.WardenAi.EMERGE_DURATION); + } + } else throw new IllegalArgumentException(flag); } level.addFreshEntity(mob); diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 5730d8b3d..fc987aedd 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -77,6 +77,16 @@ def scenarios(): 'player 12.5 -60 0.5', 'mob minecraft:villager 0.5 -60 0.5 0 51 persistent', ]) + # The warden: idle, sniffing out a player, roaring and fighting (WardenAi). + # Without finalizeSpawn's dig cooldown a warden digs straight back down. + add('warden_digs', 140, ['mob minecraft:warden 0.5 -60 0.5 0 60']) + add('warden_alone', 400, ['mob minecraft:warden 0.5 -60 0.5 0 61 digcooldown']) + add('warden_player', 600, ['player 5.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 62 digcooldown']) + add('warden_player_far', 600, ['player 14.5 -60 3.5', 'mob minecraft:warden 0.5 -60 0.5 90 63 digcooldown']) + add('warden_creative', 300, ['player 4.5 -60 0.5 creative', 'mob minecraft:warden 0.5 -60 0.5 0 64 digcooldown']) + add('warden_persistent', 400, ['player 7.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 65 persistent digcooldown']) + add('warden_emerging', 300, ['player 6.5 -60 0.5', 'mob minecraft:warden 0.5 -60 0.5 0 66 emerge']) + add('warden_cow', 600, ['mob minecraft:warden 0.5 -60 0.5 0 67 digcooldown', 'mob minecraft:cow 4.5 -60 0.5 0 68 persistent']) return s