From 0e076c7153f6dc8267df6f1d14e2d667998f273c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:17:44 +0200 Subject: [PATCH] Port the sniffer's and the ghastling's brains SnifferAi and HappyGhastAi as vanilla's Brain runs them: the sensors and their scan rates, the activities and their requirements, and every behaviour (AnimalPanic, MoveToTargetSink, FollowTemptation, AnimalMakeLove, LookAtTargetSink, RunOne and the sniffer's scenting, sniffing, searching, digging, rising and happy states) in availableBehaviorsByPriority order. Adds AirAndWaterRandomPos and the mob AI scenarios for llamas, sniffers and happy ghasts. The brain is not ticked yet. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/creatures.rs | 5 + crates/horizon-client/src/mobs.rs | 9 + .../horizon-client/src/mobs/animal_brain.rs | 1980 +++++++++++++++++ crates/horizon-client/src/mobs/goals.rs | 94 + crates/horizon-client/src/mobs/happy_ghast.rs | 69 +- crates/horizon-client/src/mobs/sniffer.rs | 474 +--- tools/test_mob_ai_parity.py | 21 + 7 files changed, 2138 insertions(+), 514 deletions(-) create mode 100644 crates/horizon-client/src/mobs/animal_brain.rs diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 0d7e34572..1e0751d5b 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -850,6 +850,11 @@ impl Game<'_> { } }, MobEvent::Breed { parent, partner } => self.breed(parent, partner), + MobEvent::BreedTarget { mob, partner } => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + horizon_client::mobs::animal_brain::set_breed_partner(m, partner); + } + } MobEvent::LeashBreak { mob, drop, sound } => self.break_leash(mob, drop, sound), MobEvent::Vibration { from, to, ticks } => { self.mob_vibration_particle(from, to, ticks) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index e6dd71e45..34ccac776 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -8,6 +8,7 @@ pub mod ai; pub mod allay; pub mod anim; +pub mod animal_brain; pub mod aquatic; pub mod body_anim; pub mod brain; @@ -537,6 +538,8 @@ pub struct Extra { pub raider: Option>, /// A villager's raid activity and gossip. pub villager: Option>, + /// The sniffer's and the ghastling's brain. + pub animal_brain: Option>, /// The mob this one rides, and the mob riding it (`getVehicle`, `getFirstPassenger`). pub mount: Option, pub rider: Option, @@ -620,6 +623,12 @@ pub struct Mob { #[derive(Clone, Debug)] pub enum MobEvent { Sound(&'static str, [f64; 3], f32, f32), + /// `AnimalMakeLove`: the partner remembers this mob as its breed target + /// and walks to it and looks at it. + BreedTarget { + mob: u32, + partner: u32, + }, /// A sound event id that is not a static string (variant sounds). SoundId(String, [f64; 3], f32, f32), AttackPlayer(f32, [f64; 3]), diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs new file mode 100644 index 000000000..5a724a518 --- /dev/null +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -0,0 +1,1980 @@ +//! The `Brain`s of the sniffer (`SnifferAi`) and the ghastling +//! (`HappyGhastAi`), ported behaviour for behaviour: memories that expire, +//! the sensors and their scan rates, the activities and their +//! requirements, and the behaviours of each activity, started and ticked in +//! vanilla's order (priority, then the activity's slot in +//! `Brain.availableBehaviorsByPriority`'s hash map, then insertion order). +//! +//! The level random (`ServerLevel.getRandom`) times behaviours; the mob's +//! own random drives positions, sounds and jumps. `RunOne` shuffles with a +//! random of its own, seeded with the brain's `shuffle_seed` when it is +//! built. +use super::{Mob, MobEvent, MobWorld, Species, Who, path::Path, sniffer}; +use horizon_core::{ + geometry::Vec3, + random::{LegacyRandom, RandomSource}, +}; + +/// `MemorySlot.NEVER_EXPIRE`. +const NEVER: i64 = i64::MAX; + +/// `MemorySlot`: a value and its time to live. +#[derive(Clone, Debug)] +pub struct Slot { + v: Option, + ttl: i64, +} +impl Default for Slot { + fn default() -> Self { + Self { + v: None, + ttl: NEVER, + } + } +} +impl Slot { + fn tick(&mut self) { + if self.v.is_some() && self.ttl != NEVER { + if self.ttl <= 0 { + self.clear(); + } else { + self.ttl -= 1; + } + } + } + pub fn set(&mut self, v: T) { + self.v = Some(v); + self.ttl = NEVER; + } + pub fn set_ttl(&mut self, v: T, ttl: i64) { + self.v = Some(v); + self.ttl = ttl; + } + pub fn set_opt(&mut self, v: Option) { + match v { + Some(v) => self.set(v), + None => self.clear(), + } + } + pub fn clear(&mut self) { + self.v = None; + self.ttl = NEVER; + } + pub fn get(&self) -> Option<&T> { + self.v.as_ref() + } + pub fn present(&self) -> bool { + self.v.is_some() + } +} +impl Slot { + pub fn value(&self) -> Option { + self.v.clone() + } +} +impl Slot> { + /// `Brain.setMemory` of a collection: an empty one erases the memory. + fn set_list(&mut self, v: Vec) { + if v.is_empty() { + self.clear(); + } else { + self.set(v); + } + } +} + +/// `PositionTracker`: an entity (`EntityTracker`: at its eyes or feet, and +/// whether its block is the one at its eyes) or a block (`BlockPosTracker`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Tracker { + Entity { + who: Who, + eye: bool, + block_eye: bool, + }, + Block([i32; 3]), +} +impl Tracker { + fn entity(who: Who, eye: bool) -> Self { + Tracker::Entity { + who, + eye, + block_eye: false, + } + } + /// `currentPosition`. + fn position(&self, w: &MobWorld) -> Option<[f64; 3]> { + match *self { + Tracker::Entity { who, eye, .. } => w.target_info(who).map(|t| { + [ + t.position.x, + if eye { t.eye_y } else { t.position.y }, + t.position.z, + ] + }), + Tracker::Block(p) => Some([ + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ]), + } + } + /// `currentBlockPosition`. + fn block(&self, w: &MobWorld) -> Option<[i32; 3]> { + match *self { + Tracker::Entity { who, block_eye, .. } => w.target_info(who).map(|t| { + if block_eye { + block_of(Vec3::new(t.position.x, t.eye_y, t.position.z)) + } else { + block_of(t.position) + } + }), + Tracker::Block(p) => Some(p), + } + } +} +fn block_of(p: Vec3) -> [i32; 3] { + [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] +} + +/// `WalkTarget`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WalkTarget { + pub target: Tracker, + pub speed: f32, + pub close: i32, +} +impl WalkTarget { + /// `new WalkTarget(Vec3, ...)`: the block containing the point. + fn point(p: [f64; 3], speed: f32, close: i32) -> Self { + Self { + target: Tracker::Block([ + p[0].floor() as i32, + p[1].floor() as i32, + p[2].floor() as i32, + ]), + speed, + close, + } + } +} + +/// `NearestVisibleLivingEntities`: the nearby entities and a lazily filled +/// cache of `Sensor.isEntityTargetable`. +#[derive(Clone, Debug, Default)] +pub struct Visible { + list: Vec, + cache: Vec<(Who, bool)>, +} + +/// The memories these brains register. +#[derive(Clone, Debug, Default)] +pub struct Memories { + pub mobs: Slot>, + pub visible_mobs: Slot, + pub nearest_players: Slot>, + pub nearest_visible_player: Slot, + pub nearest_visible_targetable_player: Slot, + pub nearest_visible_targetable_players: Slot>, + pub nearest_visible_adult: Slot, + pub walk_target: Slot, + pub look_target: Slot, + pub breed_target: Slot, + pub path: Slot, + /// `HURT_BY`: whether the damage is one of `#panic_causes`. + pub hurt_by: Slot, + pub hurt_by_entity: Slot, + pub cant_reach_walk_target_since: Slot, + pub tempting_player: Slot, + pub temptation_cooldown_ticks: Slot, + pub is_panicking: Slot, + pub sniffer_digging: Slot, + pub sniffer_sniffing_target: Slot<[i32; 3]>, + pub sniffer_happy: Slot, + pub sniff_cooldown: Slot<()>, +} +impl Memories { + fn tick(&mut self) { + self.mobs.tick(); + self.visible_mobs.tick(); + self.nearest_players.tick(); + self.nearest_visible_player.tick(); + self.nearest_visible_targetable_player.tick(); + self.nearest_visible_targetable_players.tick(); + self.nearest_visible_adult.tick(); + self.walk_target.tick(); + self.look_target.tick(); + self.breed_target.tick(); + self.path.tick(); + self.hurt_by.tick(); + self.hurt_by_entity.tick(); + self.cant_reach_walk_target_since.tick(); + self.tempting_player.tick(); + self.temptation_cooldown_ticks.tick(); + self.is_panicking.tick(); + self.sniffer_digging.tick(); + self.sniffer_sniffing_target.tick(); + self.sniffer_happy.tick(); + self.sniff_cooldown.tick(); + } +} + +/// `Activity`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Act { + Core, + Idle, + Sniff, + Dig, + Panic, +} +impl Act { + pub fn name(self) -> &'static str { + match self { + Act::Core => "core", + Act::Idle => "idle", + Act::Sniff => "sniff", + Act::Dig => "dig", + Act::Panic => "panic", + } + } +} + +/// Which brain. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Sniffer, + /// A happy ghast (the brain ticks while it is a ghastling). + Ghastling, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Sensor { + Living, + HurtBy, + Players, + Tempting, + AdultAnyType, +} +impl Kind { + /// `BRAIN_PROVIDER`'s sensors, in order (all scan every 20 ticks). + fn sensors(self) -> &'static [Sensor] { + match self { + Kind::Sniffer => &[ + Sensor::Living, + Sensor::HurtBy, + Sensor::Players, + Sensor::Tempting, + ], + Kind::Ghastling => &[ + Sensor::Living, + Sensor::HurtBy, + Sensor::Tempting, + Sensor::AdultAnyType, + Sensor::Players, + ], + } + } +} + +/// An animal's brain. +#[derive(Clone, Debug)] +pub struct Brain { + pub kind: Kind, + pub mem: Memories, + sensors: Vec<(Sensor, i64)>, + /// The active non-core activity (`CORE` is always active). + pub activity: Act, + list: Vec, +} +#[derive(Clone, Debug)] +struct Entry { + act: Act, + b: B, +} + +fn brain(m: &Mob) -> Option<&Brain> { + m.extra.animal_brain.as_deref() +} +fn brain_mut(m: &mut Mob) -> &mut Brain { + m.extra + .animal_brain + .as_deref_mut() + .expect("the animal brain is built before it is used") +} +fn mem(m: &mut Mob) -> &mut Memories { + &mut brain_mut(m).mem +} +fn mem_ref(m: &Mob) -> Option<&Memories> { + brain(m).map(|b| &b.mem) +} + +/// The brain kind a mob has, if any. +pub fn kind_of(m: &Mob) -> Option { + match m.species() { + Species::Sniffer => Some(Kind::Sniffer), + // Every happy ghast has the brain; only the ghastling's ticks. + Species::HappyGhast => Some(Kind::Ghastling), + _ => None, + } +} + +/// `Brain.Provider.makeBrain`: a new brain whose sensors' first scans are +/// delayed by draws from the mob's random, on its default activity (idle). +/// The gates shuffle with a random seeded with `shuffle_seed`. +pub fn init(m: &mut Mob, shuffle_seed: i64) { + let Some(kind) = kind_of(m) else { return }; + let sensors = kind + .sensors() + .iter() + .map(|s| (*s, i64::from(m.random.next_int_bound(20).unwrap_or(0)))) + .collect(); + let mut b = Brain { + kind, + mem: Memories::default(), + sensors, + activity: Act::Idle, + list: Vec::new(), + }; + b.list = match kind { + Kind::Sniffer => sniffer_package(shuffle_seed), + Kind::Ghastling => ghastling_package(shuffle_seed), + }; + m.extra.animal_brain = Some(Box::new(b)); +} + +/// The happy ghast grew up (`adultGhastSetup`): every running behaviour +/// stops (`Brain.stopAll`) and the memories are cleared; the brain no +/// longer ticks. +pub fn grown_up(m: &mut Mob) { + let Some(b) = m.extra.animal_brain.as_deref_mut() else { + return; + }; + for e in b.list.iter_mut() { + e.b.reset(); + } + b.mem = Memories::default(); + m.nav_stop(); +} + +/// `AnimalMakeLove.start` on the partner's side: it remembers `partner` +/// as its breed target, looks at it and walks to it +/// (`BehaviorUtils.lockGazeAndWalkToEachOther`). +pub fn set_breed_partner(m: &mut Mob, partner: u32) { + if m.extra.animal_brain.is_none() { + return; + } + let who = Who::Mob(partner); + mem(m).breed_target.set(who); + lock_gaze_and_walk(m, who, 1.0, 2); +} + +/// 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, +} + +/// `Brain.tick` then `updateActivity` (from `customServerAiStep`). +pub fn tick(m: &mut Mob, w: &MobWorld, lr: &mut LegacyRandom, events: &mut Vec) { + if brain(m).is_none() { + let seed = i64::from(m.id); + init(m, seed); + if brain(m).is_none() { + return; + } + } + // forgetOutdatedMemories + mem(m).tick(); + tick_sensors(m, w); + let mut list = std::mem::take(&mut brain_mut(m).list); + let mut cx = Bx { + w, + lr, + events, + now: w.game_time, + }; + for e in list.iter_mut() { + let active = e.act == Act::Core || e.act == brain_mut(m).activity; + if active && !e.b.running() { + e.b.try_start(m, &mut cx); + } + } + for e in list.iter_mut() { + if e.b.running() { + e.b.tick_or_stop(m, &mut cx); + } + } + brain_mut(m).list = list; + update_activity(m); + m.ai.panicking = is_panicking(m); +} + +/// `SnifferAi.updateActivity` / `HappyGhastAi.updateActivity`: +/// `setActiveActivityToFirstValid`. +fn update_activity(m: &mut Mob) { + let b = brain_mut(m); + let mm = &b.mem; + let order: &[Act] = match b.kind { + Kind::Sniffer => &[Act::Dig, Act::Sniff, Act::Idle], + Kind::Ghastling => &[Act::Panic, Act::Idle], + }; + for &a in order { + let ok = match a { + Act::Dig => { + !mm.is_panicking.present() + && !mm.walk_target.present() + && mm.sniffer_digging.present() + } + Act::Sniff => { + !mm.is_panicking.present() + && mm.sniffer_sniffing_target.present() + && mm.walk_target.present() + } + Act::Idle => b.kind != Kind::Sniffer || !mm.sniffer_digging.present(), + Act::Panic => mm.is_panicking.present(), + Act::Core => true, + }; + if ok { + b.activity = a; + break; + } + } +} + +/// `PathfinderMob.isPanicking` for a mob with this brain. +pub fn is_panicking(m: &Mob) -> bool { + mem_ref(m).is_some_and(|mm| mm.is_panicking.present()) +} +/// `Sniffer.isTempted`. +pub fn is_tempted(m: &Mob) -> bool { + mem_ref(m).is_some_and(|mm| mm.tempting_player.present()) +} +/// The explored positions are the sniffer's `SNIFFER_EXPLORED_POSITIONS`. +const EXPLORED_MAX: usize = 20; + +// ---- Sensors ------------------------------------------------------------ + +fn tick_sensors(m: &mut Mob, w: &MobWorld) { + let n = brain_mut(m).sensors.len(); + for i in 0..n { + let (sensor, fire) = { + let s = &mut brain_mut(m).sensors[i]; + s.1 -= 1; + if s.1 <= 0 { + s.1 = 20; + (s.0, true) + } else { + (s.0, false) + } + }; + if !fire { + continue; + } + match sensor { + Sensor::Living => sense_living(m, w), + Sensor::HurtBy => sense_hurt(m, w), + Sensor::Players => sense_players(m, w), + Sensor::Tempting => sense_tempting(m, w), + Sensor::AdultAnyType => sense_adult(m, w), + } + } +} +/// `NearestLivingEntitySensor`: everything alive within the follow range, +/// nearest first. +fn sense_living(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 mm = mem(m); + mm.mobs.set_list(list.clone()); + mm.visible_mobs.set(Visible { + list, + cache: Vec::new(), + }); +} +/// `Sensor.isEntityTargetable`: `TargetingConditions.forNonCombat()` within +/// the follow range, in sight. +fn targetable(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + let range = m.attrs.follow_range; + match who { + Who::Player => { + // TargetingConditions.forNonCombat(): in range (scaled by the + // player's visibility, at least 2) and in sight. + let Some(p) = &w.player else { return false }; + let visibility = if p.sneaking { 0.8 } else { 1.0 }; + let r = (range * visibility).max(2.0); + p.alive && !p.spectator && m.distance_sqr(p.position) <= r * r && m.sees(w, who) + } + Who::Mob(id) => { + let Some(s) = w.seen(id) else { return false }; + s.alive && m.distance_sqr(s.position) <= range * range && m.sees(w, who) + } + } +} +/// 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, + } + let r = targetable(m, w, who); + if let Some(v) = mem(m).visible_mobs.v.as_mut() { + v.cache.push((who, r)); + } + r +} +/// `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)) +} +/// `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) +} +/// `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()); +} +/// `HurtBySensor`: the last damage (forgotten 40 ticks after) and who did it. +fn sense_hurt(m: &mut Mob, w: &MobWorld) { + let age = i64::from(m.age); + let last = m + .last_damage + .as_ref() + .filter(|(_, t)| age - t <= 40) + .map(|(d, _)| (d.attacker, d.causes_panic())); + let mm = mem(m); + if let Some((by, panic)) = last { + mm.hurt_by.set(panic); + if let Some(by) = by { + mm.hurt_by_entity.set(by); + } + } else { + mm.hurt_by.clear(); + } + if let Some(who) = mm.hurt_by_entity.value() + && !w.target_info(who).is_some_and(|t| t.alive) + { + mm.hurt_by_entity.clear(); + } +} +/// `TemptingSensor.forAnimal`: the nearest player within the tempt range +/// holding the animal's food (and not riding it). +fn sense_tempting(m: &mut Mob, w: &MobWorld) { + // Attributes.TEMPT_RANGE: 10 for animals, 16 for the happy ghast. + let range = if m.species() == Species::HappyGhast { + 16.0 + } else { + 10.0 + }; + let food = &m.kind.food; + let holds = |item: &Option>| { + item.as_deref() + .is_some_and(|i| food.iter().any(|f| f.as_str() == i)) + }; + let tempting = w.player.as_ref().is_some_and(|p| { + p.alive + && !p.spectator + && m.distance_sqr(p.position) <= range * range + && (holds(&p.main_hand) || holds(&p.off_hand)) + && m.rider.is_none() + }); + mem(m) + .tempting_player + .set_opt(tempting.then_some(Who::Player)); +} +/// `AdultSensorAnyType`: the nearest visible adult of a followable friendly +/// type. +fn sense_adult(m: &mut Mob, w: &MobWorld) { + if !mem(m).visible_mobs.present() { + return; + } + let found = find_closest(m, w, |_, who| match who { + Who::Mob(id) => w + .seen(id) + .is_some_and(|s| !s.baby && followable_friendly(s.species)), + Who::Player => false, + }); + mem(m).nearest_visible_adult.set_opt(found); +} +/// `#followable_friendly_mobs`. +fn followable_friendly(s: Species) -> bool { + matches!( + s, + Species::Camel + | Species::Cat + | Species::Chicken + | Species::Cow + | Species::Donkey + | Species::Fox + | Species::Goat + | Species::HappyGhast + | Species::Horse + | Species::SkeletonHorse + | Species::Llama + | Species::Mule + | Species::Ocelot + | Species::Panda + | Species::Parrot + | Species::Pig + | Species::PolarBear + | Species::Rabbit + | Species::Sheep + | Species::Sniffer + | Species::Strider + | Species::Villager + | Species::Wolf + ) +} + +// ---- Behaviours ------------------------------------------------------------ + +/// `Behavior`'s running state and end time. +#[derive(Clone, Copy, 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. + fn begin(&mut self, cx: &mut Bx) { + self.running = true; + let bound = self.max.wrapping_add(1).wrapping_sub(self.min); + let d = self + .min + .wrapping_add(cx.lr.next_int_bound(bound).unwrap_or(0)); + self.end = cx.now + i64::from(d); + } + fn timed_out(&self, now: i64) -> bool { + now > self.end + } +} + +/// `RunOne`: shuffles its children by weight and starts the first that can. +#[derive(Clone, Debug)] +struct Gate { + running: bool, + random: LegacyRandom, + kids: Vec<(B, i32, f64)>, +} +impl Gate { + fn run_one(seed: i64, kids: Vec<(B, i32)>) -> Self { + Self { + running: false, + random: LegacyRandom::new(seed), + kids: kids.into_iter().map(|(b, w)| (b, w, 0.0)).collect(), + } + } + fn try_start(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + self.running = true; + // ShufflingList.shuffle: a fresh weight for each entry in the + // current order, then a stable sort. + for k in &mut self.kids { + let r = self.random.next_float(); + k.2 = -f64::from(r).powf(f64::from(1.0_f32 / k.1 as f32)); + } + self.kids.sort_by(|a, b| a.2.total_cmp(&b.2)); + for k in &mut self.kids { + if !k.0.running() && k.0.try_start(m, cx) { + break; + } + } + true + } + fn tick_or_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + for k in &mut self.kids { + if k.0.running() { + k.0.tick_or_stop(m, cx); + } + } + if !self.kids.iter().any(|k| k.0.running()) { + self.do_stop(m, cx); + } + } + fn do_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + self.running = false; + for k in &mut self.kids { + if k.0.running() { + k.0.do_stop(m, cx); + } + } + } +} + +#[derive(Clone, Debug)] +enum B { + Swim(Timed), + /// `AnimalPanic`: flying (`AirAndWaterRandomPos`) or on land, and + /// whether the sniffer's override resets its sniffing first. + AnimalPanic { + t: Timed, + fly: bool, + }, + MoveToTargetSink { + t: Timed, + cooldown: i32, + path: Option, + last_target: Option<[i32; 3]>, + speed: f32, + }, + CountDownTemptation(Timed), + MakeLove { + t: Timed, + spawn_at: i64, + }, + /// `FollowTemptation` and how close is close enough. + FollowTemptation { + t: Timed, + look_in_the_eyes: bool, + }, + LookAtTargetSink(Timed), + FeelingHappy(Timed), + Digging(Timed), + FinishedDigging(Timed), + Searching(Timed), + Scenting(Timed), + Sniffing(Timed), + DoNothing(Timed), + /// `SetWalkTargetFromLookTarget.create(speed, close)`. + WalkToLookTarget { + running: bool, + speed: f32, + close: i32, + }, + /// `SetEntityLookTarget.create(EntityType.PLAYER, 6)`. + LookAtPlayer(bool), + /// `RandomStroll.stroll` or `RandomStroll.fly`. + Stroll { + running: bool, + fly: bool, + speed: f32, + }, + /// `BabyFollowAdult.create(3..16, 1.1, memory, true)`: the nearest + /// visible player or adult. + FollowAdult { + running: bool, + player: bool, + }, + Gate(Box), +} + +impl B { + fn running(&self) -> bool { + match self { + B::Swim(t) + | B::AnimalPanic { t, .. } + | B::MoveToTargetSink { t, .. } + | B::CountDownTemptation(t) + | B::MakeLove { t, .. } + | B::FollowTemptation { t, .. } + | B::LookAtTargetSink(t) + | B::FeelingHappy(t) + | B::Digging(t) + | B::FinishedDigging(t) + | B::Searching(t) + | B::Scenting(t) + | B::Sniffing(t) + | B::DoNothing(t) => t.running, + B::WalkToLookTarget { running, .. } + | B::LookAtPlayer(running) + | B::Stroll { running, .. } + | B::FollowAdult { running, .. } => *running, + B::Gate(g) => g.running, + } + } + /// Stopped without its stop effects (the memories they would touch are + /// cleared with the rest). + fn reset(&mut self) { + match self { + B::Swim(t) + | B::AnimalPanic { t, .. } + | B::CountDownTemptation(t) + | B::MakeLove { t, .. } + | B::FollowTemptation { t, .. } + | B::LookAtTargetSink(t) + | B::FeelingHappy(t) + | B::Digging(t) + | B::FinishedDigging(t) + | B::Searching(t) + | B::Scenting(t) + | B::Sniffing(t) + | B::DoNothing(t) => t.running = false, + B::MoveToTargetSink { t, path, .. } => { + t.running = false; + *path = None; + } + B::Gate(g) => { + g.running = false; + for k in &mut g.kids { + k.0.reset(); + } + } + _ => self.set_one_shot(false), + } + } + /// A one-shot (`OneShot`) runs only until its first tick. + fn one_shot(&self) -> bool { + matches!( + self, + B::WalkToLookTarget { .. } + | B::LookAtPlayer(_) + | B::Stroll { .. } + | B::FollowAdult { .. } + ) + } + fn set_one_shot(&mut self, on: bool) { + match self { + B::WalkToLookTarget { running, .. } + | B::LookAtPlayer(running) + | B::Stroll { running, .. } + | B::FollowAdult { running, .. } => *running = on, + _ => {} + } + } + + /// `BehaviorControl.tryStart`. + fn try_start(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + if self.one_shot() { + let ok = self.trigger(m, cx); + if ok { + self.set_one_shot(true); + } + return ok; + } + let now = cx.now; + match self { + B::Gate(g) => g.try_start(m, cx), + B::Swim(t) => { + if !swim_condition(m) { + return false; + } + t.begin(cx); + true + } + B::AnimalPanic { t, .. } => { + let mm = mem(m); + if !(mm.hurt_by.get() == Some(&true) || mm.is_panicking.present()) { + return false; + } + t.begin(cx); + if brain_mut(m).kind == Kind::Sniffer { + reset_sniffing(m, cx); + } + let mm = mem(m); + mm.is_panicking.set(true); + mm.walk_target.clear(); + m.nav_stop(); + true + } + B::MoveToTargetSink { + t, + cooldown, + path, + last_target, + speed, + } => { + let mm = mem(m); + if mm.path.present() || !mm.walk_target.present() { + return false; + } + if *cooldown > 0 { + *cooldown -= 1; + return false; + } + let walk = mm.walk_target.value().unwrap(); + 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); + 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::CountDownTemptation(t) => { + if !mem(m).temptation_cooldown_ticks.present() { + return false; + } + t.begin(cx); + true + } + B::MakeLove { t, spawn_at } => { + let mm = mem(m); + if !mm.visible_mobs.present() + || mm.breed_target.present() + || mm.is_panicking.present() + { + return false; + } + if m.extra.in_love <= 0 { + return false; + } + let Some(partner) = breed_partner(m, cx.w) else { + return false; + }; + t.begin(cx); + if brain_mut(m).kind == Kind::Sniffer { + reset_sniffing(m, cx); + } + mem(m).breed_target.set(partner); + if let Who::Mob(id) = partner { + cx.events.push(MobEvent::BreedTarget { + mob: id, + partner: m.id, + }); + } + lock_gaze_and_walk(m, partner, 1.0, 2); + *spawn_at = now + 60 + i64::from(m.random.next_int_bound(50).unwrap_or(0)); + true + } + B::FollowTemptation { t, .. } => { + let mm = mem(m); + if mm.temptation_cooldown_ticks.present() + || !mm.tempting_player.present() + || mm.breed_target.present() + || mm.is_panicking.present() + { + return false; + } + t.begin(cx); + if brain_mut(m).kind == Kind::Sniffer { + reset_sniffing(m, cx); + } + true + } + B::LookAtTargetSink(t) => { + if !mem(m).look_target.present() { + return false; + } + t.begin(cx); + true + } + B::FeelingHappy(t) => { + if !mem(m).sniffer_happy.present() { + return false; + } + t.begin(cx); + transition(m, cx, sniffer::FEELING_HAPPY); + true + } + B::Digging(t) => { + let mm = mem(m); + if mm.is_panicking.present() + || mm.walk_target.present() + || !mm.sniffer_digging.present() + || mm.sniff_cooldown.present() + { + return false; + } + if !can_sniff(m) { + return false; + } + t.begin(cx); + transition(m, cx, sniffer::DIGGING); + true + } + B::FinishedDigging(t) => { + let mm = mem(m); + if mm.is_panicking.present() + || mm.walk_target.present() + || !mm.sniffer_digging.present() + || !mm.sniff_cooldown.present() + { + return false; + } + t.begin(cx); + transition(m, cx, sniffer::RISING); + true + } + B::Searching(t) => { + let mm = mem(m); + if !mm.walk_target.present() + || mm.is_panicking.present() + || !mm.sniffer_sniffing_target.present() + { + return false; + } + if !can_sniff(m) { + return false; + } + t.begin(cx); + transition(m, cx, sniffer::SEARCHING); + true + } + B::Scenting(t) => { + let mm = mem(m); + if mm.is_panicking.present() + || mm.sniffer_digging.present() + || mm.sniffer_sniffing_target.present() + || mm.sniffer_happy.present() + || mm.breed_target.present() + { + return false; + } + if is_tempted(m) { + return false; + } + t.begin(cx); + transition(m, cx, sniffer::SCENTING); + true + } + B::Sniffing(t) => { + let mm = mem(m); + if mm.walk_target.present() + || mm.sniffer_sniffing_target.present() + || mm.sniff_cooldown.present() + { + return false; + } + if m.is_baby() || !can_sniff(m) { + return false; + } + t.begin(cx); + transition(m, cx, sniffer::SNIFFING); + true + } + B::DoNothing(t) => { + t.begin(cx); + true + } + B::WalkToLookTarget { .. } + | B::LookAtPlayer(_) + | B::Stroll { .. } + | B::FollowAdult { .. } => unreachable!("one-shots trigger"), + } + } + + /// A one-shot's trigger. + fn trigger(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { + match *self { + B::WalkToLookTarget { speed, close, .. } => { + let mm = mem(m); + if mm.walk_target.present() { + return false; + } + let Some(look) = mm.look_target.value() else { + return false; + }; + mm.walk_target.set(WalkTarget { + target: look, + speed, + close, + }); + true + } + B::LookAtPlayer(_) => { + let mm = mem(m); + if mm.look_target.present() || !mm.visible_mobs.present() { + return false; + } + let w = cx.w; + let found = find_closest(m, w, |m, who| { + who == Who::Player + && w.target_info(who) + .is_some_and(|t| t.position.distance_squared(m.position) <= 36.0) + && m.rider.is_none() + }); + let Some(t) = found else { return false }; + mem(m).look_target.set(Tracker::entity(t, true)); + true + } + B::Stroll { fly, speed, .. } => { + if mem(m).walk_target.present() { + return false; + } + let pos = if fly { + let view = m.view_vector(); + m.air_and_water_random_pos(cx.w, 10, 7, -2, view[0], view[2]) + } else { + m.land_random_pos(cx.w, 10, 7) + }; + mem(m) + .walk_target + .set_opt(pos.map(|p| WalkTarget::point(p, speed, 0))); + true + } + B::FollowAdult { player, .. } => { + let mm = mem(m); + let adult = if player { + mm.nearest_visible_player.value() + } else { + mm.nearest_visible_adult.value() + }; + let Some(adult) = adult else { return false }; + if mm.walk_target.present() || !m.is_baby() { + return false; + } + let Some(at) = cx.w.target_info(adult) else { + return false; + }; + // closerThan(adult, 17) && !closerThan(adult, 3) + let d = m.distance_sqr(at.position); + if !(d < 17.0 * 17.0 && d >= 3.0 * 3.0) { + return false; + } + let mm = mem(m); + mm.walk_target.set(WalkTarget { + target: Tracker::Entity { + who: adult, + eye: true, + block_eye: true, + }, + speed: 1.1, + close: 2, + }); + mm.look_target.set(Tracker::Entity { + who: adult, + eye: true, + block_eye: true, + }); + true + } + _ => false, + } + } + + /// `BehaviorControl.tickOrStop`. + fn tick_or_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + if self.one_shot() { + self.set_one_shot(false); + return; + } + let now = cx.now; + match self { + B::Gate(g) => g.tick_or_stop(m, cx), + B::Swim(t) => { + if t.timed_out(now) || !swim_condition(m) { + self.do_stop(m, cx); + } else if m.random.next_float() < 0.8 { + m.ai.jump = true; + } + } + B::AnimalPanic { t, fly } => { + if t.timed_out(now) { + self.do_stop(m, cx); + return; + } + if m.ai.nav.is_done() { + let pos = panic_pos(m, cx.w, *fly); + if let Some(p) = pos { + mem(m).walk_target.set(WalkTarget::point(p, 2.0, 0)); + } + } + } + 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)); + if t.timed_out(now) || !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) + { + let d = dist_sqr(now_target, last); + if d > 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)); + } + } + } + B::CountDownTemptation(_) => { + let v = mem(m).temptation_cooldown_ticks.value(); + match v { + Some(v) if v > 0 => mem(m).temptation_cooldown_ticks.set(v - 1), + _ => self.do_stop(m, cx), + } + } + B::MakeLove { spawn_at, .. } => { + let Some(partner) = mem(m).breed_target.value() else { + self.do_stop(m, cx); + return; + }; + let ok = cx.w.target_info(partner).is_some_and(|t| t.alive) + && can_mate_with(m, cx.w, partner) + && visible_contains(m, cx.w, partner) + && now <= *spawn_at + && !is_panicking(m) + && !partner_panicking(cx.w, partner); + if !ok { + self.do_stop(m, cx); + return; + } + lock_gaze_and_walk(m, partner, 1.0, 2); + if let Some(t) = cx.w.target_info(partner) + && m.distance_sqr(t.position) < 9.0 + && now >= *spawn_at + { + // spawnChildFromBreeding: the egg (or baby), and both + // parents rest (finalizeSpawnChildFromBreeding). + let Who::Mob(id) = partner else { return }; + m.extra.in_love = 0; + m.extra.age = 6000; + cx.events.push(MobEvent::Breed { + parent: m.id, + partner: id, + }); + mem(m).breed_target.clear(); + } + } + B::FollowTemptation { + look_in_the_eyes, .. + } => { + let mm = mem(m); + let still = mm.tempting_player.present() + && !mm.breed_target.present() + && !mm.is_panicking.present(); + if !still { + self.do_stop(m, cx); + return; + } + let eyes = *look_in_the_eyes; + let player = mm.tempting_player.value().unwrap(); + mm.look_target.set(Tracker::entity(player, true)); + let close = follow_temptation_close(m); + let near = + cx.w.target_info(player) + .is_some_and(|t| m.distance_sqr(t.position) < close * close); + let speed = if brain_mut(m).kind == Kind::Sniffer { + 1.25 + } else { + 1.25 + }; + let mm = mem(m); + if near { + mm.walk_target.clear(); + } else { + mm.walk_target.set(WalkTarget { + target: Tracker::Entity { + who: player, + eye: eyes, + block_eye: eyes, + }, + speed, + close: 2, + }); + } + } + B::LookAtTargetSink(t) => { + let visible = match mem(m).look_target.value() { + Some(look) => tracker_visible(m, cx.w, look), + None => false, + }; + if t.timed_out(now) || !visible { + self.do_stop(m, cx); + } else if let Some(at) = mem(m).look_target.value().and_then(|l| l.position(cx.w)) { + m.look_at(at); + } + } + B::FeelingHappy(t) | B::Scenting(t) | B::DoNothing(t) => { + if t.timed_out(now) { + self.do_stop(m, cx); + } + } + B::Digging(t) => { + let ok = + mem(m).sniffer_digging.present() && can_dig(m, cx.w) && m.extra.in_love <= 0; + if t.timed_out(now) || !ok { + self.do_stop(m, cx); + } + } + B::FinishedDigging(t) => { + if t.timed_out(now) || !mem(m).sniffer_digging.present() { + self.do_stop(m, cx); + } + } + B::Searching(t) => { + let still = if !can_sniff(m) { + transition(m, cx, sniffer::IDLING); + false + } else { + let w = cx.w; + let mm = mem(m); + match ( + mm.walk_target.value().and_then(|t| t.target.block(w)), + mm.sniffer_sniffing_target.value(), + ) { + (Some(a), Some(b)) => a == b, + _ => false, + } + }; + if t.timed_out(now) || !still { + self.do_stop(m, cx); + } + } + B::Sniffing(t) => { + if t.timed_out(now) || !can_sniff(m) { + self.do_stop(m, cx); + } + } + B::WalkToLookTarget { .. } + | B::LookAtPlayer(_) + | B::Stroll { .. } + | B::FollowAdult { .. } => {} + } + } + + /// `BehaviorControl.doStop`. + fn do_stop(&mut self, m: &mut Mob, cx: &mut Bx) { + if self.one_shot() { + self.set_one_shot(false); + return; + } + let now = cx.now; + match self { + B::Gate(g) => g.do_stop(m, cx), + B::Swim(t) | B::DoNothing(t) => t.running = false, + B::AnimalPanic { t, .. } => { + t.running = false; + mem(m).is_panicking.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::CountDownTemptation(t) => { + t.running = false; + mem(m).temptation_cooldown_ticks.clear(); + } + B::MakeLove { t, spawn_at } => { + t.running = false; + let mm = mem(m); + mm.breed_target.clear(); + mm.walk_target.clear(); + mm.look_target.clear(); + *spawn_at = 0; + } + B::FollowTemptation { t, .. } => { + t.running = false; + let mm = mem(m); + mm.temptation_cooldown_ticks.set(100); + mm.walk_target.clear(); + mm.look_target.clear(); + } + B::LookAtTargetSink(t) => { + t.running = false; + mem(m).look_target.clear(); + } + B::FeelingHappy(t) => { + t.running = false; + transition(m, cx, sniffer::IDLING); + mem(m).sniffer_happy.clear(); + } + B::Digging(t) => { + t.running = false; + if t.timed_out(now) { + mem(m).sniff_cooldown.set_ttl((), 9600); + } else { + reset_sniffing(m, cx); + } + } + B::FinishedDigging(t) => { + t.running = false; + let finished = t.timed_out(now); + transition(m, cx, sniffer::IDLING); + if finished { + // onDiggingComplete: storeExploredPosition(getOnPos()). + let p = sniffer::on_pos(m); + m.extra.positions.truncate(EXPLORED_MAX); + m.extra.positions.insert(0, p); + } + let mm = mem(m); + mm.sniffer_digging.clear(); + mm.sniffer_happy.set(true); + } + B::Searching(t) => { + t.running = false; + if can_dig(m, cx.w) && can_sniff(m) { + mem(m).sniffer_digging.set(true); + } + let mm = mem(m); + mm.walk_target.clear(); + mm.sniffer_sniffing_target.clear(); + } + B::Scenting(t) => { + t.running = false; + transition(m, cx, sniffer::IDLING); + } + B::Sniffing(t) => { + t.running = false; + let finished = t.timed_out(now); + transition(m, cx, sniffer::IDLING); + if finished && let Some(p) = dig_position(m, cx.w) { + let mm = mem(m); + mm.sniffer_sniffing_target.set(p); + mm.walk_target.set(WalkTarget { + target: Tracker::Block(p), + speed: 1.25, + close: 0, + }); + } + } + B::WalkToLookTarget { .. } + | B::LookAtPlayer(_) + | B::Stroll { .. } + | B::FollowAdult { .. } => {} + } + } +} + +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 dist_sqr(a: [i32; 3], b: [i32; 3]) -> i64 { + let d = |i: usize| i64::from(a[i] - b[i]); + d(0) * d(0) + d(1) * d(1) + d(2) * d(2) +} +fn manhattan(a: [i32; 3], b: [i32; 3]) -> i32 { + (a[0] - b[0]).abs() + (a[1] - b[1]).abs() + (a[2] - b[2]).abs() +} +/// `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 +} +/// `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) + } + Tracker::Block(_) => 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 +} +/// `AnimalPanic.getPanicPos`: on land 5 blocks out and 4 up or down, or +/// for a flyer the air and water around it ahead (water first when burning +/// is not reproduced: no fire reaches these scenarios). +fn panic_pos(m: &mut Mob, w: &MobWorld, fly: bool) -> Option<[f64; 3]> { + if fly { + let view = m.view_vector(); + m.air_and_water_random_pos(w, 5, 4, 0, view[0], view[2]) + } else { + m.land_random_pos(w, 5, 4) + } +} +/// `BehaviorUtils.lockGazeAndWalkToEachOther` (this mob's half; the +/// partner's comes with the breed-target event). +fn lock_gaze_and_walk(m: &mut Mob, partner: Who, speed: f32, close: i32) { + let t = Tracker::entity(partner, true); + let mm = mem(m); + mm.look_target.set(t); + mm.walk_target.set(WalkTarget { + target: t, + speed, + close, + }); +} +/// `FollowTemptation`'s close-enough distance. +fn follow_temptation_close(m: &mut Mob) -> f64 { + match brain_mut(m).kind { + Kind::Sniffer => { + if m.is_baby() { + 2.5 + } else { + 3.5 + } + } + Kind::Ghastling => 3.0, + } +} +fn can_mate_with(m: &Mob, w: &MobWorld, partner: Who) -> bool { + let Who::Mob(id) = partner else { return false }; + let Some(s) = w.seen(id) else { return false }; + s.species == m.species() + && s.in_love + && m.extra.in_love > 0 + && sniffer::can_mate_state(sniffer::state(m)) + && sniffer::can_mate_state(s.variant) +} +fn partner_panicking(_w: &MobWorld, _partner: Who) -> bool { + false +} +/// `AnimalMakeLove.findValidBreedPartner`. +fn breed_partner(m: &mut Mob, w: &MobWorld) -> Option { + find_closest(m, w, |m, who| can_mate_with(m, w, who)) +} + +// ---- The sniffer -------------------------------------------------------- + +/// `Sniffer.transitionTo`: the state and its sound. +fn transition(m: &mut Mob, cx: &mut Bx, to: u8) { + let at = [m.position.x, m.position.y, m.position.z]; + let sound = |name: &'static str, pitch: f32| MobEvent::Sound(name, at, 1.0, pitch); + match to { + sniffer::FEELING_HAPPY => cx.events.push(sound("entity.sniffer.happy", 1.0)), + sniffer::SCENTING => { + let pitch = if m.is_baby() { 1.3 } else { 1.0 }; + cx.events.push(sound("entity.sniffer.scenting", pitch)); + } + sniffer::SNIFFING => cx.events.push(sound("entity.sniffer.sniffing", 1.0)), + // onDiggingStart: the seed drops 120 ticks in. + sniffer::DIGGING => m.extra.ints[3] = m.age as i32 + 120, + sniffer::RISING => cx.events.push(sound("entity.sniffer.digging_stop", 1.0)), + _ => {} + } + sniffer::set_state(m, to); +} +/// `SnifferAi.resetSniffing`. +fn reset_sniffing(m: &mut Mob, cx: &mut Bx) { + let mm = mem(m); + mm.sniffer_digging.clear(); + mm.sniffer_sniffing_target.clear(); + transition(m, cx, sniffer::IDLING); +} +/// `Sniffer.canSniff`. +fn can_sniff(m: &Mob) -> bool { + !is_tempted(m) + && !is_panicking(m) + && !m.fluids.in_water + && m.extra.in_love <= 0 + && m.on_ground + && !m.extra.passenger + && m.extra.leash.is_none() +} +/// `Sniffer.canDig(BlockPos)`: diggable, unexplored and reachable. +fn can_dig_at(m: &mut Mob, w: &MobWorld, p: [i32; 3]) -> bool { + w.has_tag( + "minecraft:sniffer_diggable_block", + w.block_name(p[0], p[1], p[2]), + ) && !m.extra.positions.contains(&p) + && m.create_path_to(w, p, 1).is_some_and(|path| path.reached) +} +/// `Sniffer.canDig()`. +fn can_dig(m: &mut Mob, w: &MobWorld) -> bool { + if is_panicking(m) + || is_tempted(m) + || m.is_baby() + || m.fluids.in_water + || !m.on_ground + || m.extra.passenger + { + return false; + } + let head = sniffer::head_block(m); + can_dig_at(m, w, [head[0], head[1] - 1, head[2]]) +} +/// `Sniffer.calculateDigPosition`: the first of five ever wider land +/// positions whose block below can be dug. +fn dig_position(m: &mut Mob, w: &MobWorld) -> Option<[i32; 3]> { + for idx in 0..5 { + let Some(p) = m.land_random_pos(w, 10 + 2 * idx, 3) else { + continue; + }; + let below = [ + p[0].floor() as i32, + p[1].floor() as i32 - 1, + p[2].floor() as i32, + ]; + if can_dig_at(m, w, below) { + return Some(below); + } + } + None +} + +/// `SnifferAi.getActivities`, in `availableBehaviorsByPriority` order: by +/// priority (`ActivityData.create(CORE, 0, ...)` numbers the core +/// behaviours 0, 1, 2...), then by the activity's bucket in the 16-bucket +/// `HashMap` (core 1, dig 3, idle 5, sniff 6, panic 15), +/// then in insertion order. +fn sniffer_package(seed: i64) -> Vec { + let e = |act: Act, b: B| Entry { act, b }; + let mut l = vec![ + // Priority 0: core, dig, idle, sniff. + e(Act::Core, B::Swim(Timed::new(60, 60))), + e(Act::Dig, B::Digging(Timed::new(160, 180))), + e(Act::Dig, B::FinishedDigging(Timed::new(40, 40))), + e( + Act::Idle, + B::MakeLove { + t: Timed::new(110, 110), + spawn_at: 0, + }, + ), + e(Act::Sniff, B::Searching(Timed::new(600, 600))), + // Priority 1. + e( + Act::Core, + B::AnimalPanic { + t: Timed::new(100, 120), + fly: false, + }, + ), + e( + Act::Idle, + B::FollowTemptation { + t: Timed::new(60, 60), + look_in_the_eyes: false, + }, + ), + // Priority 2. + e(Act::Core, move_to_target_sink(500, 700)), + e(Act::Idle, B::LookAtTargetSink(Timed::new(45, 90))), + // Priority 3. + e(Act::Core, B::CountDownTemptation(Timed::new(60, 60))), + e(Act::Idle, B::FeelingHappy(Timed::new(40, 100))), + ]; + // Priority 4. + l.push(e( + Act::Idle, + B::Gate(Box::new(Gate::run_one( + seed, + vec![ + ( + B::WalkToLookTarget { + running: false, + speed: 1.0, + close: 3, + }, + 2, + ), + (B::Scenting(Timed::new(40, 80)), 1), + (B::Sniffing(Timed::new(40, 80)), 1), + (B::LookAtPlayer(false), 1), + ( + B::Stroll { + running: false, + fly: false, + speed: 1.0, + }, + 1, + ), + (B::DoNothing(Timed::new(5, 20)), 2), + ], + ))), + )); + l +} +/// `HappyGhastAi.getActivities`, in `availableBehaviorsByPriority` order. +fn ghastling_package(seed: i64) -> Vec { + let e = |act: Act, b: B| Entry { act, b }; + vec![ + // Priority 0. + e(Act::Core, B::Swim(Timed::new(60, 60))), + // Priority 1. + e( + Act::Core, + B::AnimalPanic { + t: Timed::new(100, 120), + fly: true, + }, + ), + e( + Act::Idle, + B::FollowTemptation { + t: Timed::new(60, 60), + look_in_the_eyes: true, + }, + ), + // Priority 2. + e(Act::Core, B::LookAtTargetSink(Timed::new(45, 90))), + e( + Act::Idle, + B::FollowAdult { + running: false, + player: true, + }, + ), + // Priority 3. + e(Act::Core, move_to_target_sink(150, 250)), + e( + Act::Idle, + B::FollowAdult { + running: false, + player: false, + }, + ), + // Priority 4. + e(Act::Core, B::CountDownTemptation(Timed::new(60, 60))), + e( + Act::Idle, + B::Gate(Box::new(Gate::run_one( + seed, + vec![ + ( + B::Stroll { + running: false, + fly: true, + speed: 1.0, + }, + 1, + ), + ( + B::WalkToLookTarget { + running: false, + speed: 1.0, + close: 3, + }, + 1, + ), + ], + ))), + ), + ] +} +fn move_to_target_sink(min: i32, max: i32) -> B { + B::MoveToTargetSink { + t: Timed::new(min, max), + cooldown: 0, + path: None, + last_target: None, + speed: 0.0, + } +} + +// ---- Debug output (the mob AI harness) ------------------------------------ + +fn pos(p: [i32; 3]) -> String { + format!("{},{},{}", p[0], p[1], p[2]) +} +fn who(w: Who) -> String { + match w { + Who::Player => "player".into(), + Who::Mob(id) => format!("e{id}"), + } +} +fn tracker(t: Tracker) -> String { + match t { + Tracker::Entity { who: e, .. } => who(e), + Tracker::Block(p) => pos(p), + } +} + +/// The active activities and the memories, as the mob AI oracle prints +/// them. +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 == NEVER { + 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 n = |l: &Vec| format!("n{}", l.len()); + slot!("mobs", mm.mobs, n); + slot!("visible_mobs", mm.visible_mobs, |_: &Visible| { + "NearestVisibleLivingEntities".to_string() + }); + slot!("nearest_players", mm.nearest_players, n); + 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, + n + ); + slot!( + "nearest_visible_adult", + mm.nearest_visible_adult, + |e: &Who| who(*e) + ); + slot!("walk_target", mm.walk_target, |t: &WalkTarget| format!( + "{}/{:x}/{}", + tracker(t.target), + t.speed.to_bits(), + t.close + )); + slot!("look_target", mm.look_target, |t: &Tracker| tracker(*t)); + slot!("breed_target", mm.breed_target, |e: &Who| who(*e)); + slot!("path", mm.path, |p: &Path| format!("path{}", pos(p.target))); + slot!("hurt_by", mm.hurt_by, |_: &bool| "DamageSource".to_string()); + slot!("hurt_by_entity", mm.hurt_by_entity, |e: &Who| who(*e)); + slot!( + "cant_reach_walk_target_since", + mm.cant_reach_walk_target_since, + |t: &i64| t.to_string() + ); + slot!("tempting_player", mm.tempting_player, |e: &Who| who(*e)); + slot!( + "temptation_cooldown_ticks", + mm.temptation_cooldown_ticks, + |t: &i32| t.to_string() + ); + slot!("is_panicking", mm.is_panicking, |b: &bool| b.to_string()); + slot!("sniffer_digging", mm.sniffer_digging, |b: &bool| b + .to_string()); + slot!( + "sniffer_sniffing_target", + mm.sniffer_sniffing_target, + |p: &[i32; 3]| pos(*p) + ); + slot!("sniffer_happy", mm.sniffer_happy, |b: &bool| b.to_string()); + slot!("sniff_cooldown", mm.sniff_cooldown, |_: &()| "u" + .to_string()); + if b.kind == Kind::Sniffer && !m.extra.positions.is_empty() { + put( + "sniffer_explored_positions", + format!("n{}", m.extra.positions.len()), + NEVER, + ); + } + out.sort(); + Some((acts.join("|"), out.join(" "))) +} diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index c5439479b..50adf62e5 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -304,6 +304,100 @@ impl Mob { let water = w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water; (!water && self.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p) } + /// The home a mob stays near (`Mob.getHomePosition` / `getHomeRadius`): + /// only happy ghasts keep one here. + fn home(&self) -> Option<([i32; 3], i32)> { + if self.species() != Species::HappyGhast { + return None; + } + self.extra.home.map(|h| (h, self.extra.ints[4])) + } + /// `Entity.getViewVector(0)`: `calculateViewVector(xRotO, yRotO)`. + pub fn view_vector(&self) -> [f64; 3] { + use horizon_core::geometry::trig::Mth; + let to_rad = std::f32::consts::PI / 180.0; + let x = self.previous_head_pitch * to_rad; + let y = -self.previous_yaw * to_rad; + let (y_cos, y_sin, x_cos, x_sin) = (y.mcos(), y.msin(), x.mcos(), x.msin()); + [ + f64::from(y_sin * x_cos), + f64::from(-x_sin), + f64::from(y_cos * x_cos), + ] + } + /// AirAndWaterRandomPos.getPos: within the radians of a direction, kept + /// near home, moved up out of solid blocks and free of path maluses. + pub fn air_and_water_random_pos( + &mut self, + w: &MobWorld, + h: i32, + v: i32, + fly_height: i32, + xd: f64, + zd: f64, + ) -> Option<[f64; 3]> { + let home = self.home(); + let at = self.position; + let within = |c: [i32; 3], r: f64, p: [f64; 3]| { + let d = |i: usize| f64::from(c[i]) + 0.5 - p[i]; + d(0) * d(0) + d(1) * d(1) + d(2) * d(2) < r * r + }; + // GoalUtils.mobRestricted + let restrict = home + .is_some_and(|(c, r)| within(c, f64::from(r) + f64::from(h) + 1.0, [at.x, at.y, at.z])); + self.pick_best(w, |m| { + let d = m.random_direction_within( + 0.0, + f64::from(h), + v, + fly_height, + xd, + zd, + std::f64::consts::FRAC_PI_2, + )?; + // RandomPos.generateRandomPosTowardDirection, toward home. + let (mut xt, mut zt) = (f64::from(d[0]), f64::from(d[2])); + if let Some((c, _)) = home + && h > 1 + { + let half = f64::from(h) / 2.0; + if m.position.x > f64::from(c[0]) { + xt -= m.random.next_double() * half; + } else { + xt += m.random.next_double() * half; + } + if m.position.z > f64::from(c[2]) { + zt -= m.random.next_double() * half; + } else { + zt += m.random.next_double() * half; + } + } + let mut p = [ + (xt + m.position.x).floor() as i32, + (f64::from(d[1]) + m.position.y).floor() as i32, + (zt + m.position.z).floor() as i32, + ]; + if p[1] < crate::chunk::MIN_Y || p[1] >= 320 { + return None; + } + // GoalUtils.isRestricted: Mob.isWithinHome(BlockPos). + if restrict && let Some((c, r)) = home { + let dd = |i: usize| i64::from(c[i] - p[i]); + let r = i64::from(r); + if dd(0) * dd(0) + dd(1) * dd(1) + dd(2) * dd(2) >= r * r { + return None; + } + } + // RandomPos.moveUpOutOfSolid + if w.solid(p[0], p[1], p[2]) { + p[1] += 1; + while p[1] <= 319 && w.solid(p[0], p[1], p[2]) { + p[1] += 1; + } + } + (m.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p) + }) + } /// LandRandomPos.getPos pub fn land_random_pos(&mut self, w: &MobWorld, h: i32, v: i32) -> Option<[f64; 3]> { self.pick_best(w, |m| { diff --git a/crates/horizon-client/src/mobs/happy_ghast.rs b/crates/horizon-client/src/mobs/happy_ghast.rs index 463d29edf..56d5946f5 100644 --- a/crates/horizon-client/src/mobs/happy_ghast.rs +++ b/crates/horizon-client/src/mobs/happy_ghast.rs @@ -3,10 +3,10 @@ //! ghastling follows players and adults, a harnessed adult can be ridden and //! flown, healing is slow (fast in the rain) and `HappyGhastModel`. use super::{ - Mob, MobEvent, MobWorld, Species, + Mob, MobEvent, MobWorld, anim::{Poses, State}, control::{MoveKind, Operation}, - goals::{Cx, Float, Goal, LOOK, MOVE, Panic, Stroll, Tempt, goal_clone}, + goals::{Cx, Float, Goal, LOOK, MOVE, goal_clone}, nav::NavKind, }; use horizon_core::{ @@ -25,8 +25,11 @@ pub const AIR_SPEED: f32 = 0.05 * 5.0 / 3.0; pub fn register(m: &mut Mob) { setup(m, m.is_baby()); } -/// `adultGhastSetup` and `babyGhastSetup`. +/// `adultGhastSetup` and `babyGhastSetup`: the ghastling flies with a +/// `FlyingMoveControl` and has no goals (its brain drives it); the adult +/// floats with `GhastMoveControl` and three goals, its brain stopped. fn setup(m: &mut Mob, baby: bool) { + let was = m.extra.scratch[0]; m.extra.scratch[0] = if baby { 1 } else { 2 }; m.ai.goals.clear(); m.ai.nav.stop(); @@ -36,20 +39,15 @@ fn setup(m: &mut Mob, baby: bool) { max_turn: 180.0, hovers: true, }; + // BabyFlyingPathNavigation. m.ai.nav.kind = NavKind::Flying; m.ai.nav.can_float = true; m.ai.nav.required_path_length = 48.0; - let tempt = m.kind.food.clone(); - let g = &mut m.ai.goals; - g.add(0, Float); - g.add(0, Panic::new(2.0)); - let mut t = Tempt::new(1.25, tempt, false); - t.stop_distance = 3.0; - g.add(1, t); - g.add(2, FollowAdult::default()); - g.add(4, Stroll::flying(1.0)); return; } + if was == 1 { + super::animal_brain::grown_up(m); + } m.ai.mov.kind = MoveKind::Custom; m.ai.nav.kind = NavKind::Ground; let g = &mut m.ai.goals; @@ -274,53 +272,6 @@ impl Goal for FloatAround { m.ai.mov.set_wanted(t.x, t.y, t.z, 1.0); } } -/// `BabyFollowAdult`: a ghastling drifts toward the nearest player or adult -/// until it is a few blocks away. -#[derive(Clone, Debug, Default)] -struct FollowAdult { - close: f64, -} -impl FollowAdult { - fn target(m: &Mob, cx: &Cx) -> Option { - let player = - cx.w.player - .as_ref() - .filter(|p| p.alive && !p.spectator && m.distance_sqr(p.position) <= 32.0 * 32.0) - .map(|p| p.position); - player.or_else(|| { - cx.w.nearby(m.position, 32.0, |s| { - s.species == Species::HappyGhast && !s.baby - }) - .next() - .map(|s| s.position) - }) - } -} -impl Goal for FollowAdult { - goal_clone!(); - fn flags(&self) -> u8 { - MOVE - } - fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - m.is_baby() - && Self::target(m, cx).is_some_and(|t| { - let close = if self.close > 0.0 { self.close } else { 16.0 }; - m.position.distance_squared(t) > close * close - }) - } - fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - Self::target(m, cx).is_some_and(|t| m.position.distance_squared(t) > 9.0) - } - fn start(&mut self, m: &mut Mob, _: &mut Cx) { - // UniformInt.of(3, 16). - self.close = f64::from(3 + m.random.next_int_bound(14).unwrap_or(0)); - } - fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { - if let Some(t) = Self::target(m, cx) { - m.nav_move_to(cx.w, [t.x, t.y, t.z], 1.1); - } - } -} /// What a rider asks (`getRiddenInput`, `tickRidden`). pub fn ridden(m: &mut Mob) { let Some(r) = m.rider else { return }; diff --git a/crates/horizon-client/src/mobs/sniffer.rs b/crates/horizon-client/src/mobs/sniffer.rs index e8049b2d3..c9954669c 100644 --- a/crates/horizon-client/src/mobs/sniffer.rs +++ b/crates/horizon-client/src/mobs/sniffer.rs @@ -3,13 +3,10 @@ //! digging up a seed, the explored positions, laying eggs when bred, and //! `SnifferModel`'s keyframe animations. use super::{ - Mob, MobEvent, MobWorld, + Mob, MobEvent, anim::{Poses, State}, - brain::{Sink, Ttl, WalkTarget, duration}, - goals::{Breed, Cx, Float, Goal, Panic, Tempt, goal_clone}, keyframes::Animation, }; -use horizon_core::random::RandomSource; use std::collections::HashMap; // Sniffer state: `variant` the state (below), `scratch[0]` the state the @@ -24,15 +21,14 @@ pub const SEARCHING: u8 = 4; pub const DIGGING: u8 = 5; pub const RISING: u8 = 6; -const SNIFF_COOLDOWN: i32 = 9600; /// `Sniffer.getBabyStartAge`. pub const BABY_START_AGE: i32 = -48000; pub fn state(m: &Mob) -> u8 { m.extra.variant } -fn set_state(m: &mut Mob, s: u8) { - m.extra.variant = s; +fn now(m: &Mob) -> i32 { + m.age as i32 } /// `Sniffer.getDefaultDimensions`: lower while digging. pub fn digging(m: &Mob) -> bool { @@ -44,468 +40,36 @@ pub fn register(m: &mut Mob) { m.set_malus(PathType::Water, -1.0); m.set_malus(PathType::OnTopOfPowderSnow, -1.0); m.set_malus(PathType::DamageCautious, -1.0); - let tempt = m.kind.tempt.clone(); - let g = &mut m.ai.goals; - g.add(0, Float); - g.add(0, SnifferPanic(Panic::new(2.0))); - g.add( - 0, - Brain { - walk: None, - sink: Sink::new(500, 700), - look: None, - look_until: 0, - digging: false, - happy: false, - cooldown: Ttl::default(), - sniff_target: None, - run: Run::None, - until: 0, - breed: Breed::new(1.0), - tempt: Tempt::new(1.25, tempt, false), - love_on: false, - tempt_on: false, - }, - ); } -/// The core's `AnimalPanic`, forgetting any sniffing when it starts. -#[derive(Clone, Debug)] -struct SnifferPanic(Panic); -impl Goal for SnifferPanic { - goal_clone!(); - fn flags(&self) -> u8 { - self.0.flags() - } - fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - self.0.can_use(m, cx) - } - fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - self.0.can_continue(m, cx) - } - fn start(&mut self, m: &mut Mob, cx: &mut Cx) { - set_state(m, IDLING); - self.0.start(m, cx) - } - fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { - self.0.stop(m, cx) - } -} -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Run { - None, - Digging, - FinishedDigging, - Searching, - Happy, - Scenting, - Sniffing, - DoNothing, -} -#[derive(Clone, Debug)] -struct Brain { - walk: Option, - sink: Sink, - /// `LOOK_TARGET` and the end of `LookAtTargetSink`'s run (0 when not running). - look: Option<[f64; 3]>, - look_until: i32, - /// `SNIFFER_DIGGING`, `SNIFFER_HAPPY`, `SNIFF_COOLDOWN`, `SNIFFER_SNIFFING_TARGET`. - digging: bool, - happy: bool, - cooldown: Ttl, - sniff_target: Option<[i32; 3]>, - /// The timed behaviour running and when it times out. - run: Run, - until: i32, - breed: Breed, - tempt: Tempt, - love_on: bool, - tempt_on: bool, -} -impl Goal for Brain { - goal_clone!(); - fn flags(&self) -> u8 { - 0 - } - fn can_use(&mut self, _: &mut Mob, _: &mut Cx) -> bool { - true - } - fn every_tick(&self) -> bool { - true - } - fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { - self.brain(m, cx); - } -} -fn now(m: &Mob) -> i32 { - m.age as i32 -} -fn sound(m: &Mob, cx: &mut Cx, name: &'static str, pitch: f32) { - cx.events - .push(MobEvent::Sound(name, m.center(), 1.0, pitch)); +/// `Sniffer.setState`. +pub fn set_state(m: &mut Mob, s: u8) { + m.extra.variant = s; } /// `Sniffer.getOnPos`: the block under its feet. -fn on_pos(m: &Mob) -> [i32; 3] { +pub fn on_pos(m: &Mob) -> [i32; 3] { [ m.position.x.floor() as i32, - (m.position.y - 0.2).floor() as i32, + (m.position.y - f64::from(0.2_f32)).floor() as i32, m.position.z.floor() as i32, ] } -/// `Sniffer.getHeadBlock`: 2.25 blocks ahead of it, a little above its feet. +/// `Sniffer.getHeadBlock`: 2.25 blocks along `getForward()`, at its feet +/// plus 0.2. pub fn head_block(m: &Mob) -> [i32; 3] { - let (yaw, pitch) = (m.yaw.to_radians(), m.head_pitch.to_radians()); - let forward = [ - f64::from(-yaw.sin() * pitch.cos()), - f64::from(-pitch.sin()), - f64::from(yaw.cos() * pitch.cos()), - ]; + use horizon_core::geometry::trig::Mth; + // Vec3.directionFromRotation(xRot, yRot). + let to_rad = std::f32::consts::PI / 180.0; + let y = -m.yaw * to_rad - std::f32::consts::PI; + let x = -m.head_pitch * to_rad; + let (y_cos, y_sin) = (y.mcos(), y.msin()); + let x_cos = -x.mcos(); + let forward = [f64::from(y_sin * x_cos), f64::from(y_cos * x_cos)]; [ (m.position.x + forward[0] * 2.25).floor() as i32, (m.position.y + f64::from(0.2_f32)).floor() as i32, - (m.position.z + forward[2] * 2.25).floor() as i32, + (m.position.z + forward[1] * 2.25).floor() as i32, ] } -impl Brain { - fn tempted(&self) -> bool { - self.tempt_on - } - /// `Sniffer.canSniff`. - fn can_sniff(&self, m: &Mob) -> bool { - !self.tempted() - && !m.ai.panicking - && !m.fluids.in_water - && m.extra.in_love <= 0 - && m.on_ground - && m.rider.is_none() - && m.extra.leash.is_none() - } - /// `Sniffer.canDig(BlockPos)`: diggable, unexplored and reachable. - fn can_dig_at(&self, m: &mut Mob, w: &MobWorld, p: [i32; 3]) -> bool { - w.has_tag( - "minecraft:sniffer_diggable_block", - w.block_name(p[0], p[1], p[2]), - ) && !m.extra.positions.contains(&p) - && m.create_path_to(w, p, 1).is_some_and(|path| path.reached) - } - /// `Sniffer.canDig`. - fn can_dig(&self, m: &mut Mob, w: &MobWorld) -> bool { - if m.ai.panicking - || self.tempted() - || m.is_baby() - || m.fluids.in_water - || !m.on_ground - || m.rider.is_some() - { - return false; - } - let head = head_block(m); - self.can_dig_at(m, w, [head[0], head[1] - 1, head[2]]) - } - /// `Sniffer.calculateDigPosition`. - fn dig_position(&self, m: &mut Mob, w: &MobWorld) -> Option<[i32; 3]> { - for idx in 0..5 { - let Some(p) = m.land_random_pos(w, 10 + 2 * idx, 3) else { - continue; - }; - let below = [ - p[0].floor() as i32, - p[1].floor() as i32 - 1, - p[2].floor() as i32, - ]; - if self.can_dig_at(m, w, below) { - return Some(below); - } - } - None - } - fn transition(&mut self, m: &mut Mob, cx: &mut Cx, to: u8) { - match to { - FEELING_HAPPY => sound(m, cx, "entity.sniffer.happy", 1.0), - SCENTING => { - let pitch = if m.is_baby() { 1.3 } else { 1.0 }; - sound(m, cx, "entity.sniffer.scenting", pitch) - } - SNIFFING => sound(m, cx, "entity.sniffer.sniffing", 1.0), - DIGGING => m.extra.ints[3] = now(m) + 120, - RISING => sound(m, cx, "entity.sniffer.digging_stop", 1.0), - _ => {} - } - set_state(m, to); - } - /// `SnifferAi.resetSniffing`. - fn reset_sniffing(&mut self, m: &mut Mob, cx: &mut Cx) { - self.digging = false; - self.sniff_target = None; - self.transition(m, cx, IDLING); - } - fn brain(&mut self, m: &mut Mob, cx: &mut Cx) { - self.cooldown.tick(); - // Tempted: the tempting player memory while the goal runs. - if m.ai.panicking { - self.walk = None; - self.sink.stop(m, &mut self.walk); - self.love_on = false; - self.tempt_on = false; - } else { - self.start_behaviours(m, cx); - } - self.sink.tick(m, cx, &mut self.walk); - self.tick_running(m, cx); - } - /// `Brain.startEachNonRunningBehavior` for the first valid activity. - fn start_behaviours(&mut self, m: &mut Mob, cx: &mut Cx) { - let n = now(m); - // DIG, SNIFF, IDLE. - let dig = self.digging && self.walk.is_none(); - let sniff = self.sniff_target.is_some() && self.walk.is_some(); - if dig { - if self.run == Run::None && !self.cooldown.present() && self.can_sniff(m) { - self.run = Run::Digging; - self.until = n + duration(m, 160, 180); - self.transition(m, cx, DIGGING); - } - if self.run == Run::None && self.cooldown.present() { - self.run = Run::FinishedDigging; - self.until = n + 40; - self.transition(m, cx, RISING); - } - return; - } - if sniff { - if self.run == Run::None && self.can_sniff(m) { - self.run = Run::Searching; - self.until = n + 600; - self.transition(m, cx, SEARCHING); - } - return; - } - if self.digging { - return; - } - // IDLE: love, tempt, look at the target, feeling happy, one of the rest. - if !self.love_on && !self.tempt_on && self.breed.can_use(m, cx) { - self.reset_sniffing(m, cx); - self.breed.start(m, cx); - self.love_on = true; - } - if !self.love_on && !self.tempt_on && self.tempt.can_use(m, cx) { - self.reset_sniffing(m, cx); - self.tempt.start(m, cx); - self.tempt_on = true; - } - if self.look.is_some() && self.look_until == 0 { - self.look_until = n + duration(m, 45, 90); - } - if self.run == Run::None && self.happy { - self.run = Run::Happy; - self.until = n + duration(m, 40, 100); - self.transition(m, cx, FEELING_HAPPY); - } - if self.run == Run::None { - self.run_one(m, cx); - } - } - /// The idle `RunOne`: a weighted random pick among what can start. - fn run_one(&mut self, m: &mut Mob, cx: &mut Cx) { - let n = now(m); - // (weight, option) - let mut options: Vec<(i32, u8)> = Vec::new(); - if self.look.is_some() && self.walk.is_none() { - options.push((2, 0)); - } - if !self.happy && !self.love_on && !self.tempted() && self.sniff_target.is_none() { - options.push((1, 1)); - } - if self.walk.is_none() - && self.sniff_target.is_none() - && !self.cooldown.present() - && !m.is_baby() - && self.can_sniff(m) - { - options.push((1, 2)); - } - if cx.w.player.as_ref().is_some_and(|p| { - p.alive && !p.creative && m.distance_sqr(p.position) <= 36.0 && !p.spectator - }) { - options.push((1, 3)); - } - if self.walk.is_none() { - options.push((1, 4)); - } - options.push((2, 5)); - let total: i32 = options.iter().map(|o| o.0).sum(); - // A weighted pick from the high bits (`WeightedList.getRandom`). - let mut roll = ((m.random.next_float() * total as f32) as i32).min(total - 1); - let mut pick = options[0].1; - for (w, o) in &options { - if roll < *w { - pick = *o; - break; - } - roll -= w; - } - match pick { - // SetWalkTargetFromLookTarget(1.0, 3). - 0 => { - if let Some(l) = self.look { - self.walk = Some(WalkTarget::new( - [ - l[0].floor() as i32, - l[1].floor() as i32, - l[2].floor() as i32, - ], - 1.0, - 3, - )); - } - } - 1 => { - self.run = Run::Scenting; - self.until = n + duration(m, 40, 80); - self.transition(m, cx, SCENTING); - } - 2 => { - self.run = Run::Sniffing; - self.until = n + duration(m, 40, 80); - self.transition(m, cx, SNIFFING); - } - // SetEntityLookTarget(PLAYER, 6). - 3 => { - if let Some(p) = &cx.w.player { - self.look = Some(p.eye); - self.look_until = 0; - } - } - // RandomStroll.stroll(1.0). - 4 => { - if let Some(p) = m.land_random_pos(cx.w, 10, 7) { - self.walk = Some(WalkTarget::new( - [ - p[0].floor() as i32, - p[1].floor() as i32, - p[2].floor() as i32, - ], - 1.0, - 0, - )); - } - } - _ => { - self.run = Run::DoNothing; - self.until = n + duration(m, 5, 20); - } - } - } - /// `Brain.tickRunningBehaviors`. - fn tick_running(&mut self, m: &mut Mob, cx: &mut Cx) { - let n = now(m); - let timed_out = n > self.until; - // The delegated idle behaviours. - if self.love_on { - if self.breed.can_continue(m, cx) { - self.breed.tick(m, cx); - } else { - self.breed.stop(m, cx); - self.love_on = false; - } - } - if self.tempt_on { - self.tempt.stop_distance = if m.is_baby() { 2.5 } else { 3.5 }; - if self.tempt.can_continue(m, cx) { - self.tempt.tick(m, cx); - } else { - self.tempt.stop(m, cx); - self.tempt_on = false; - } - } - // LookAtTargetSink. - if self.look_until != 0 { - if let Some(l) = self.look - && n <= self.look_until - { - m.look_at(l); - } else { - self.look = None; - self.look_until = 0; - } - } - match self.run { - Run::None => {} - Run::Digging => { - let ok = self.digging && self.can_dig(m, cx.w) && m.extra.in_love <= 0; - if timed_out || !ok { - if timed_out { - self.cooldown.set(SNIFF_COOLDOWN); - } else { - self.reset_sniffing(m, cx); - } - self.run = Run::None; - } - } - Run::FinishedDigging => { - if timed_out || !self.digging { - self.transition(m, cx, IDLING); - // onDiggingComplete: remember the spot when it finished. - if timed_out { - let p = on_pos(m); - m.extra.positions.insert(0, p); - m.extra.positions.truncate(21); - } - self.digging = false; - self.happy = true; - self.run = Run::None; - } - } - Run::Searching => { - let still = if !self.can_sniff(m) { - self.transition(m, cx, IDLING); - false - } else { - match (self.walk, self.sniff_target) { - (Some(w), Some(t)) => w.pos == t, - _ => false, - } - }; - if timed_out || !still { - if self.can_dig(m, cx.w) && self.can_sniff(m) { - self.digging = true; - } - self.sink.stop(m, &mut self.walk); - self.sniff_target = None; - self.run = Run::None; - } - } - Run::Happy => { - if timed_out { - self.transition(m, cx, IDLING); - self.happy = false; - self.run = Run::None; - } - } - Run::Scenting => { - if timed_out { - self.transition(m, cx, IDLING); - self.run = Run::None; - } - } - Run::Sniffing => { - if timed_out || !self.can_sniff(m) { - self.transition(m, cx, IDLING); - if timed_out && let Some(p) = self.dig_position(m, cx.w) { - self.sniff_target = Some(p); - self.walk = Some(WalkTarget::new(p, 1.25, 0)); - } - self.run = Run::None; - } - } - Run::DoNothing => { - if timed_out { - self.run = Run::None; - } - } - } - } -} /// `Sniffer.tick` and `Sniffer.aiStep` additions: the animation states, /// the dropped seed and the water malus. pub fn ai_step(m: &mut Mob, events: &mut Vec) { diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index bee2af785..957605492 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -73,6 +73,27 @@ def scenarios(): 'player 12.5 -60 0.5', 'mob minecraft:villager 0.5 -60 0.5 0 51 persistent', ]) + # Llamas and trader llamas: strolling, looking at the player, a baby following its parent and a + # llama hunting a wolf (LlamaAttackWolfGoal) and spitting at it. + for species, seed in [('llama', 61), ('trader_llama', 62)]: + add(f'{species}_player', 200, ['player 6.5 -60 0.5', f'mob minecraft:{species} 0.5 -60 0.5 0 {seed} persistent']) + add(f'{species}_alone', 200, [f'mob minecraft:{species} 0.5 -60 0.5 90 {seed * 7 + 1} persistent']) + add('llama_family', 200, ['mob minecraft:llama 0.5 -60 0.5 0 63 persistent', + 'mob minecraft:llama 6.5 -60 2.5 0 64 persistent baby']) + add('llama_wolf', 200, ['mob minecraft:llama 0.5 -60 0.5 0 65 persistent', + 'mob minecraft:wolf 8.5 -60 0.5 0 66 persistent']) + # Sniffers on diggable grass: scenting, sniffing, searching and digging. + add('sniffer_player', 400, ['player 8.5 -60 0.5', 'mob minecraft:sniffer 0.5 -60 0.5 0 71 persistent']) + for i, seed in enumerate([72, 73, 74]): + add(f'sniffer_alone_{i}', 600, [f'mob minecraft:sniffer 0.5 -60 0.5 {90 * i} {seed} persistent']) + add('sniffer_baby', 300, ['mob minecraft:sniffer 0.5 -60 0.5 0 75 persistent baby']) + # Happy ghasts float above the grass; ghastlings follow players and adults. + add('happy_ghast_player', 200, ['player 6.5 -60 0.5', 'mob minecraft:happy_ghast 0.5 -55 0.5 0 81 persistent']) + add('happy_ghast_alone', 200, ['mob minecraft:happy_ghast 0.5 -55 0.5 90 82 persistent']) + add('ghastling_player', 200, ['player 8.5 -60 0.5', 'mob minecraft:happy_ghast 0.5 -57 0.5 0 83 persistent baby']) + add('ghastling_alone', 200, ['mob minecraft:happy_ghast 0.5 -57 0.5 0 84 persistent baby']) + add('ghastling_adult', 200, ['mob minecraft:happy_ghast 10.5 -55 0.5 0 85 persistent', + 'mob minecraft:happy_ghast 0.5 -57 0.5 0 86 persistent baby']) return s