diff --git a/crates/horizon-client/examples/entity_anim_fixture.rs b/crates/horizon-client/examples/entity_anim_fixture.rs index 3e7176520..cb541f28c 100644 --- a/crates/horizon-client/examples/entity_anim_fixture.rs +++ b/crates/horizon-client/examples/entity_anim_fixture.rs @@ -8,7 +8,7 @@ use horizon_client::mobs::{ anim::{self, Poses, State}, aquatic, body_anim as b_anim, equine, guardian, keyframes::AnimationState, - shulker, species, tame, + shulker, sniffer, species, tame, }; use horizon_core::geometry::Vec3; use serde_json::{Value, json}; @@ -182,6 +182,30 @@ fn entity_state(mob: &mut Mob, species: Species, case: &Value) { mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32); } } + Species::Sniffer => { + if flag("isSearching") { + mob.extra.variant = sniffer::SEARCHING; + } + // Sniffer's animation states, in `sniffer::anim`'s order. + for (i, k) in [ + "feelingHappyAnimationState", + "scentingAnimationState", + "sniffingAnimationState", + "diggingAnimationState", + "risingAnimationState", + ] + .into_iter() + .enumerate() + { + mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32); + } + } + Species::HappyGhast => { + mob.extra.head = case["bodyItem"].as_str().map(Into::into); + if flag("isRidden") { + mob.rider = Some(Default::default()); + } + } Species::Witch if flag("isHoldingItem") => { mob.extra.main_hand = Some("minecraft:potion".into()); } @@ -225,8 +249,12 @@ fn main() -> horizon_client::Result<()> { } let base = base.replace("undead_horse#", "zombie_horse#"); // The breeze's wind and eyes and the creaking's eyes are layers of - // the species' own model class. - let base = base.replace("#wind", "#main").replace("#eyes", "#main"); + // the species' own model class; LlamaDecorLayer's model animates like + // the llama. + let base = base + .replace("#wind", "#main") + .replace("#eyes", "#main") + .replace("#decor", "#main"); let base = base.trim_start_matches("cold_").trim_start_matches("warm_"); let Some(def) = species::ALL.iter().find(|d| { d.model == layer diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index e4ab1d317..df0d70b62 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -56,6 +56,7 @@ struct Scenario { spawning: bool, /// The player hits a mob for 1 at the start of a tick: (tick, mob index). hurts: Vec<(i32, usize)>, + hand: Option, mobs: Vec, } @@ -101,6 +102,8 @@ fn parse(text: &str) -> Vec { } else if let Some(t) = opt.strip_prefix("turn=") { let (tick, yaw) = t.split_once(',').unwrap(); s.turn = Some((tick.parse().unwrap(), yaw.parse().unwrap())); + } else if let Some(item) = opt.strip_prefix("hand=") { + s.hand = Some(item.to_owned()); } else { panic!("unknown player option {opt}"); } @@ -262,6 +265,11 @@ fn seen(m: &Mob) -> Seen { .flatten(), profession: m.extra.variant2, xp: horizon_client::mobs::villager::xp(m), + stats: [ + f64::from(m.attrs.max_health), + m.extra.vector[0], + m.attrs.speed, + ], } } @@ -465,9 +473,10 @@ 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) + let brain = horizon_client::mobs::villager_brain::describe(m) .or_else(|| horizon_client::mobs::monster_brain::describe(m)) - { + .or_else(|| horizon_client::mobs::animal_brain::describe(m)); + if let Some((acts, mem)) = brain { let _ = write!(out, "\tact {acts}\tmem {mem}"); } out.push('\n'); @@ -590,6 +599,15 @@ fn main() -> horizon_client::Result<()> { match flag.as_str() { "persistent" => m.persistent = true, "noai" => m.no_ai = true, + "inlove" => m.extra.in_love = 600, + "tame" => m.extra.tame = true, + x if x.starts_with("age=") => m.extra.age = x[4..].parse().unwrap(), + x if x.starts_with("strength=") => m.extra.variant2 = x[9..].parse().unwrap(), + "leashed" => m.extra.leash = Some(horizon_client::mobs::leash::Holder::Player), + x if x.starts_with("leashto=") => { + let n: u32 = x[8..].parse().unwrap(); + m.extra.leash = Some(horizon_client::mobs::leash::Holder::Mob(100_000 + n)); + } other => panic!("unknown mob flag {other}"), } } @@ -609,6 +627,10 @@ fn main() -> horizon_client::Result<()> { spec.seed, ); } + // The same for the sniffer's and the happy ghast's brains. + if horizon_client::mobs::animal_brain::kind_of(&m).is_some() { + horizon_client::mobs::animal_brain::init(&mut m, spec.seed); + } mobs.push(m); } let mut player = s.player.map(|p| { @@ -624,7 +646,7 @@ fn main() -> horizon_client::Result<()> { creative: s.creative, sneaking: false, look: [0.0, 0.0, 1.0], - main_hand: None, + main_hand: s.hand.as_deref().map(Into::into), off_hand: None, head: None, armor_cover: 0.0, @@ -643,6 +665,35 @@ fn main() -> horizon_client::Result<()> { for (i, m) in mobs.iter().enumerate() { print(&mut out, 0, i, m); } + // The MobWorld every step sees, over a snapshot of the mobs. + macro_rules! mob_world { + ($snapshot:expr) => { + MobWorld { + teams: Default::default(), + world: &world, + registry, + facts: &facts, + collision: &collision, + data: &data, + player: player.clone(), + others: $snapshot, + daylight: (s.time.rem_euclid(24000)) < 12000, + game_time: world.game_time, + day_time: world.day_time, + raining: s.rain, + thundering: s.thunder, + nether: false, + block_tags: &items.block_tags, + biomes: &biomes, + mob_griefing: true, + difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0), + end: false, + world_seed: 0, + // FlatLevelSource.getSeaLevel. + sea_level: -63, + } + }; + } for t in 1..=s.ticks { world.game_time += 1; let mut heart_events_later: Vec = Vec::new(); @@ -665,31 +716,8 @@ fn main() -> horizon_client::Result<()> { p.look = [f64::from(sin), -0.0, f64::from(cos)]; p.yaw = yaw; } - let snapshot: Vec = mobs.iter().filter(|m| !m.removed).map(seen).collect(); - let w = MobWorld { - teams: Default::default(), - world: &world, - registry, - facts: &facts, - collision: &collision, - data: &data, - player: player.clone(), - others: &snapshot, - daylight: (s.time.rem_euclid(24000)) < 12000, - game_time: world.game_time, - day_time: world.day_time, - raining: s.rain, - thundering: s.thunder, - nether: false, - block_tags: &items.block_tags, - biomes: &biomes, - mob_griefing: true, - difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0), - end: false, - world_seed: 0, - // FlatLevelSource.getSeaLevel. - sea_level: -63, - }; + let mut snapshot: Vec = mobs.iter().filter(|m| !m.removed).map(seen).collect(); + let w = mob_world!(&snapshot); let mut events = Vec::new(); let mut heart_events = Vec::new(); let mut added = Vec::new(); @@ -739,10 +767,12 @@ fn main() -> horizon_client::Result<()> { #[allow(unused_mut)] // filled only with the rng-trace feature let mut traces: Vec = Vec::new(); let mut pushes = Vec::new(); - for (i, m) in mobs.iter_mut().enumerate() { - if m.removed { + for i in 0..mobs.len() { + if mobs[i].removed { continue; } + let w = mob_world!(&snapshot); + let m = &mut mobs[i]; horizon_client::mobs::apply_mob_pushes(m, &mut pushes); let from = events.len(); #[cfg(feature = "rng-trace")] @@ -756,14 +786,21 @@ fn main() -> horizon_client::Result<()> { } } horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes); - let _ = i; if !alive { m.removed = true; } + horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from); + // ServerLevel ticks entities one after another: the ones + // after this mob see it as it is now. + if let Some(e) = snapshot.iter_mut().find(|e| e.id == mobs[i].id) { + *e = seen(&mobs[i]); + e.alive &= !mobs[i].removed; + } } for m in &mut mobs { horizon_client::mobs::apply_mob_pushes(m, &mut pushes); } + let w = mob_world!(&snapshot); // ServerLevel.tickBlockEntities: the hearts (none ticks once uprooted). heart_events.append(&mut heart_events_later); for (at, h) in &mut hearts { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index c5cf7ec02..48d00f287 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -135,6 +135,11 @@ pub(super) fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen { .flatten(), profession: m.extra.variant2, xp: horizon_client::mobs::villager::xp(m), + stats: [ + f64::from(m.attrs.max_health), + m.extra.vector[0], + m.attrs.speed, + ], } } impl Game<'_> { @@ -449,7 +454,7 @@ impl Game<'_> { } self.tick_raids(); let uuid = self.level.player_uuid; - let snapshot: Vec = self.mobs.iter().map(|m| seen(m, uuid)).collect(); + let mut snapshot: Vec = self.mobs.iter().map(|m| seen(m, uuid)).collect(); let mut events = Vec::new(); let mut mobs = std::mem::take(&mut self.mobs); let mut dead = Vec::new(); @@ -457,24 +462,34 @@ impl Game<'_> { // the like draw from it, and it goes on from where they left it. let mut scratch = self.world.random.clone(); { - let w = self.mob_world_base(&snapshot); let mut pushes = Vec::new(); - mobs.retain_mut(|m| { + let mut keep = Vec::with_capacity(mobs.len()); + for i in 0..mobs.len() { + let w = self.mob_world_base(&snapshot); + let m = &mut mobs[i]; if !w .world .loaded(m.position.x.floor() as i32, m.position.z.floor() as i32) { - return !m.hostile() || m.persistent; + keep.push(!m.hostile() || m.persistent); + continue; } horizon_client::mobs::apply_mob_pushes(m, &mut pushes); let from = events.len(); - let keep = m.tick(&w, &mut scratch, &mut events); + let kept = m.tick(&w, &mut scratch, &mut events); horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes); - if !keep && !m.alive() && !m.removed { + if !kept && !m.alive() && !m.removed { dead.push(m.clone()); } - keep - }); + keep.push(kept); + // ServerLevel ticks entities one after another: the ones + // after this mob see it as it is now. + snapshot[i] = seen(m, uuid); + snapshot[i].alive &= kept; + horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from); + } + let mut flags = keep.into_iter(); + mobs.retain(|_| flags.next().unwrap_or(true)); for m in &mut mobs { horizon_client::mobs::apply_mob_pushes(m, &mut pushes); } @@ -896,7 +911,21 @@ impl Game<'_> { } } }, - MobEvent::Breed { parent, partner } => self.breed(parent, partner), + MobEvent::Breed { + parent, + partner, + llama, + } => self.breed(parent, partner, llama), + MobEvent::LockGaze { mob, partner } => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + horizon_client::mobs::animal_brain::lock_gaze(m, 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) @@ -981,7 +1010,12 @@ impl Game<'_> { } } /// Animal.spawnChildFromBreeding - fn breed(&mut self, parent: u32, partner: u32) { + fn breed( + &mut self, + parent: u32, + partner: u32, + llama: Option>, + ) { let Some(p) = self.mobs.iter().find(|m| m.id == parent).cloned() else { return; }; @@ -1034,6 +1068,12 @@ impl Game<'_> { && let Some(child) = self.mobs.iter_mut().find(|m| m.id == id) { child.extra.age = -24000; + // A llama's baby was drawn in the parent's tick, with the + // experience. + if let Some(o) = llama { + horizon_client::mobs::llama::apply_offspring(child, &o); + return; + } if horizon_client::mobs::equine::is_equine(p.species()) { let other = q.clone().unwrap_or_else(|| p.clone()); let mut r = self.world.random.clone(); diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index 33cc5fcf6..d86c41255 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -1943,7 +1943,7 @@ impl Game<'_> { } // Leashable.dropLeash: a lead item at the leashed entity's feet. let drop = |game: &mut Self, j: usize| { - if game.mobs[j].extra.leash.take().is_some() { + if horizon_client::mobs::leash::remove(&mut game.mobs[j]).is_some() { let at = game.mobs[j].position; game.spawn_at_location(at, 0.0, ItemStack::new("minecraft:lead", 1)); } diff --git a/crates/horizon-client/src/game/ghasts.rs b/crates/horizon-client/src/game/ghasts.rs index c324ecfef..40b4a574d 100644 --- a/crates/horizon-client/src/game/ghasts.rs +++ b/crates/horizon-client/src/game/ghasts.rs @@ -48,6 +48,9 @@ impl Game<'_> { let id = self.mobs[index].id; self.break_leash(id, true, false); let was_empty = self.mobs[index].rider.is_none(); + // addPassenger: the rider is not standing on top, so no still + // timeout. + self.mobs[index].extra.counter = 0; self.yaw = self.mobs[index].yaw; self.riding = Some(id); self.mount.reset_jump(); @@ -62,6 +65,12 @@ impl Game<'_> { } /// Getting off lands on top of it. pub(super) fn dismount_happy_ghast(&mut self, id: u32) { + // removePassenger: held still for half a second, and with no one + // aboard the ghast forgets its home. + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.extra.counter = 10; + m.ai.home = None; + } let Some(m) = self.mobs.iter().find(|m| m.id == id) else { return; }; diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs index 77ccc9a97..699b362f8 100644 --- a/crates/horizon-client/src/game/leads.rs +++ b/crates/horizon-client/src/game/leads.rs @@ -76,7 +76,7 @@ impl Game<'_> { let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else { return; }; - if m.extra.leash.take().is_none() { + if horizon_client::mobs::leash::remove(m).is_none() { return; } let at = [m.position.x, m.position.y, m.position.z]; diff --git a/crates/horizon-client/src/game/sniffers.rs b/crates/horizon-client/src/game/sniffers.rs index 683ab733f..61325ede6 100644 --- a/crates/horizon-client/src/game/sniffers.rs +++ b/crates/horizon-client/src/game/sniffers.rs @@ -10,20 +10,19 @@ use horizon_client::{ use horizon_core::random::RandomSource; impl Game<'_> { - /// An egg item at the parent, a plop and some experience. + /// The egg item at the parent (`Sniffer.spawnChildFromBreeding`; the + /// brain already played the plop and dropped the experience). pub(super) fn lay_sniffer_egg(&mut self, parent: &Mob) { let at = [parent.position.x, parent.position.y, parent.position.z]; + // new ItemEntity(level, x, y, z, stack): a little random push. + let vx = self.world.random.next_double() * 0.2 - 0.1; + let vz = self.world.random.next_double() * 0.2 - 0.1; self.spawn_item( ItemStack::new("minecraft:sniffer_egg", 1), at, - [0.0, 0.2, 0.0], + [vx, 0.2, vz], 10, ); - let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 0.5; - self.audio - .play("minecraft:block.sniffer_egg.plop", Some(at), 1.0, pitch); - let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32; - self.spawn_orbs(at, xp); } /// A snifflet where the egg was. pub(super) fn hatch_sniffer(&mut self, pos: [i32; 3]) { @@ -42,8 +41,10 @@ impl Game<'_> { m.head_yaw = yaw; } } - /// `Sniffer.emitDiggingParticles`: block dust and the digging sound - /// between the 1.7th and the 6th second of the digging animation. + /// The sniffer's client-side effects: `SnifferSoundInstance` when it + /// starts digging, `Sniffer.emitDiggingParticles` (block dust and the + /// block's hit sound between the 1.7th and the 6th second of the + /// digging animation) and `playSearchingSound`. pub(super) fn tick_sniffer_effects(&mut self) { let Some(camera) = self.player.as_ref().map(|p| p.position) else { return; @@ -52,14 +53,27 @@ impl Game<'_> { let m = &self.mobs[i]; if m.species() != Species::Sniffer || !m.alive() - || !sniffer::digging(m) + || m.silent || m.position.distance_squared(camera) > 32.0 * 32.0 { continue; } + let at = [m.position.x, m.position.y, m.position.z]; + if sniffer::state(m) == sniffer::SEARCHING && m.age.is_multiple_of(20) { + self.audio + .play("minecraft:entity.sniffer.searching", Some(at), 1.0, 1.0); + continue; + } + if !sniffer::digging(m) { + continue; + } let Some(ms) = m.anim.states[3].millis(m.age as f32) else { continue; }; + if ms == 0 { + self.audio + .play("minecraft:entity.sniffer.digging", Some(at), 1.0, 1.0); + } if ms <= 1700 || ms >= 6000 { continue; } @@ -68,19 +82,19 @@ impl Game<'_> { let Some((sprite, tint)) = self.particle_sprite(below) else { continue; }; - let at = [ + let dust = [ f64::from(head[0]) + 0.5, f64::from(head[1]) + 0.5 - f64::from(0.65_f32), f64::from(head[2]) + 0.5, ]; for _ in 0..30 { let particle = - Particle::terrain(&mut self.world.random, at, [0.0; 3], sprite.clone(), tint); + Particle::terrain(&mut self.world.random, dust, [0.0; 3], sprite.clone(), tint); self.particles.push(particle); } if self.mobs[i].age.is_multiple_of(10) { - self.audio - .play("minecraft:entity.sniffer.digging", Some(at), 0.5, 0.5); + let hit = self.res.facts.get(below).sounds.hit.clone(); + self.audio.play(&hit, Some(at), 0.5, 0.5); } } } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 804f3aad6..1178deb6b 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; @@ -545,6 +546,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, @@ -639,6 +642,18 @@ pub enum MobEvent { target: u32, item: &'static str, }, + /// `AnimalMakeLove`: the partner remembers this mob as its breed target + /// and walks to it and looks at it. + BreedTarget { + mob: u32, + partner: u32, + }, + /// `BehaviorUtils.lockGazeAndWalkToEachOther`'s other half: the partner + /// looks at this mob and walks to it. + LockGaze { + mob: u32, + partner: u32, + }, /// A sound event id that is not a static string (variant sounds). SoundId(String, [f64; 3], f32, f32), /// `Level.playLocalSound`: a sound the client plays for itself, never @@ -740,6 +755,9 @@ pub enum MobEvent { Breed { parent: u32, partner: u32, + /// A llama's baby, drawn from the parent's random as + /// `Llama.getBreedOffspring` does. + llama: Option>, }, /// Replace a block by name (sheep turning grass to dirt), optionally with /// the destroy effect. @@ -914,9 +932,13 @@ pub struct Seen { /// A villager's `POTENTIAL_JOB_SITE` and `MEETING_POINT`. pub potential_job: Option<[i32; 3]>, pub meeting: Option<[i32; 3]>, - /// A villager's profession (index into `render::PROFESSIONS`) and experience. + /// `variant2`: a villager's profession (index into + /// `render::PROFESSIONS`), a llama's strength. And a villager's experience. pub profession: u8, pub xp: i32, + /// `MAX_HEALTH`, `JUMP_STRENGTH` and `MOVEMENT_SPEED` base values (a + /// horse's breeding stock). + pub stats: [f64; 3], } impl Mob { /// `EntityType.getCategory`'s name. @@ -962,6 +984,41 @@ pub fn apply_mob_pushes(m: &mut Mob, pending: &mut Vec<(u32, Vec3)>) { false }); } +/// Applies the brain memories a mob's tick set on other mobs (from event +/// index `from` on), at once: vanilla sets them on the other entity during +/// the tick, before the mobs after it tick. +pub fn apply_brain_events(mobs: &mut [Mob], events: &mut Vec, from: usize) { + let mut i = from; + while i < events.len() { + match events[i] { + MobEvent::BreedTarget { mob, partner } => { + if let Some(m) = mobs.iter_mut().find(|m| m.id == mob) { + animal_brain::set_breed_partner(m, partner); + } + events.remove(i); + } + MobEvent::LockGaze { mob, partner } => { + if let Some(m) = mobs.iter_mut().find(|m| m.id == mob) { + animal_brain::lock_gaze(m, partner); + } + events.remove(i); + } + // Animal.finalizeSpawnChildFromBreeding: the partner rests and + // forgets it at once (the game still makes the baby). + MobEvent::Breed { + parent, partner, .. + } => { + if let Some(m) = mobs.iter_mut().find(|m| m.id == partner) { + m.extra.age = 6000; + m.extra.in_love = 0; + animal_brain::forget_breed_target(m, parent); + } + i += 1; + } + _ => i += 1, + } + } +} /// The player as mobs see it. #[derive(Clone, Debug)] pub struct PlayerView { diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 7b276542c..9c825d61b 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -19,6 +19,9 @@ use horizon_core::{ #[derive(Clone, Debug, Default)] pub struct Ai { + /// `Mob.homePosition` and `homeRadius`: where a restricted mob stays + /// (a lead's holder, a happy ghast's float area). + pub home: Option<([i32; 3], i32)>, pub goals: GoalSelector, pub targets: GoalSelector, pub nav: Navigation, @@ -563,6 +566,10 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & .is_some_and(|t| t.position.distance_squared(m.position) > 121.0); super::witch::ai_step(m, events, far); } + // AbstractHorse.aiStep: the tail swishes now and then (moveTail). + if super::equine::is_equine(m.species()) { + let _ = m.random.next_int_bound(200); + } // Monster.aiStep: updateNoActionTime (Raider: always +2). if is_monster(m.species()) && (super::raider::is_raider(m.species()) || super::hostile::mob_brightness(m, w) > 0.5) @@ -608,7 +615,12 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & // AgeableMob.aiStep if m.alive() { if m.extra.age < 0 { + let (bw, bh, _) = m.dims(); m.extra.age += 1; + // setAge at the age boundary: refreshDimensions. + if m.extra.age >= 0 { + m.fudge_position_after_size_change(w, bw, bh); + } } else if m.extra.age > 0 { m.extra.age -= 1; } @@ -619,13 +631,18 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & if m.extra.in_love > 0 { m.extra.in_love -= 1; if m.extra.in_love % 10 == 0 { + // The heart's speed and getRandomX/Y/Z, drawn even on the server. + let (w, h) = (f64::from(m.width()), f64::from(m.height())); + let r = &mut m.random; + for _ in 0..3 { + let _ = r.next_gaussian(); + } + let x = m.position.x + w * (2.0 * r.next_double() - 1.0); + let y = m.position.y + h * r.next_double() + 0.5; + let z = m.position.z + w * (2.0 * r.next_double() - 1.0); events.push(MobEvent::Particles { kind: "heart", - at: [ - m.position.x, - m.position.y + f64::from(m.height()) + 0.5, - m.position.z, - ], + at: [x, y, z], count: 1, }); } @@ -737,6 +754,10 @@ fn server_ai_step( events: &mut Vec, ) { m.ai.no_action_time += 1; + // A happy ghast set up for its age (ageBoundaryReached runs at once). + if m.species() == Species::HappyGhast { + super::happy_ghast::ensure_setup(m); + } // A saddled mount follows its rider instead of its goals. if super::equine::controlled(m) { super::equine::ridden_step(m); @@ -774,6 +795,11 @@ fn server_ai_step( super::villager_brain::tick(m, w, level_random, events); let _ = m.random.next_int_bound(100); } + // Sniffer and HappyGhast.customServerAiStep: the brain (a happy ghast's + // only while it is a ghastling), then updateActivity. + if m.species() == Species::Sniffer || m.species() == Species::HappyGhast && m.is_baby() { + super::animal_brain::tick(m, w, level_random, events); + } { let mut cx = Cx { w, events }; custom_server_ai_step(m, &mut cx); @@ -951,6 +977,17 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 { if family(m.species()) == Family::Guardian && w.fluid(p[0], p[1], p[2]) == Fluid::Water { return 10.0 + light(); } + // HappyGhast.getWalkTargetValue: open air, best just above the ground. + if m.species() == Species::HappyGhast { + let air = |y: i32| w.facts.is_air(w.world.block(p[0], y, p[2])); + return if !air(p[1]) { + 0.0 + } else if air(p[1] - 1) && !air(p[1] - 2) { + 10.0 + } else { + 5.0 + }; + } // AbstractNautilus and Creaking.getWalkTargetValue: everywhere alike. if matches!( m.species(), diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index bc033ede0..ca340fbaa 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -466,7 +466,8 @@ pub fn setup( Anim::CopperGolem => super::copper_golem::anim(m, s, p, w_anims), Anim::HappyGhast => super::happy_ghast::anim(m, s, p), Anim::Nautilus => super::nautilus::anim(m, s, p, w_anims), - Anim::Llama => super::llama::anim(m, s, p), + // body_anim::llama runs first. + Anim::Llama => quadruped(p, s), Anim::Warden => super::warden::anim(m, s, p, w_anims), Anim::Allay => super::allay::anim(m, s, p), Anim::Creaking => super::creaking::anim(m, s, p, w_anims), 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..c37fa469e --- /dev/null +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -0,0 +1,2016 @@ +//! 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); +} + +/// `AnimalMakeLove.tick` after the birth: the partner forgets this mob. +pub fn forget_breed_target(m: &mut Mob, partner: u32) { + if m.extra.animal_brain.is_some() && mem(m).breed_target.value() == Some(Who::Mob(partner)) { + mem(m).breed_target.clear(); + } +} +/// The partner's half of `lockGazeAndWalkToEachOther`. +pub fn lock_gaze(m: &mut Mob, partner: u32) { + if m.extra.animal_brain.is_none() { + return; + } + lock_gaze_and_walk(m, Who::Mob(partner), 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 Who::Mob(id) = partner { + cx.events.push(MobEvent::LockGaze { + mob: id, + partner: m.id, + }); + } + 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, + llama: None, + }); + if brain_mut(m).kind == Kind::Sniffer { + // Sniffer.spawnChildFromBreeding: the experience + // (finalizeSpawnChildFromBreeding), then the plop, + // both from the parent's random; the game lays the + // egg. + let at = [m.position.x, m.position.y, m.position.z]; + let xp = 1 + m.random.next_int_bound(7).unwrap_or(0); + cx.events.push(MobEvent::Experience { + at, + amount: xp as u32, + }); + let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 0.5; + cx.events + .push(MobEvent::Sound("block.sniffer_egg.plop", at, 1.0, pitch)); + } + 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/caravan.rs b/crates/horizon-client/src/mobs/caravan.rs index 3ba4055a5..15f01d59e 100644 --- a/crates/horizon-client/src/mobs/caravan.rs +++ b/crates/horizon-client/src/mobs/caravan.rs @@ -55,20 +55,21 @@ fn first_is_leashed(cx: &Cx, caravan: u32, leashed: bool, counter: i32) -> bool #[derive(Clone, Debug)] pub struct FollowCaravan { speed: f64, - base_speed: f64, dist_check: i32, } impl FollowCaravan { pub fn new(speed: f64) -> Self { Self { speed, - base_speed: speed, dist_check: 0, } } } impl Goal for FollowCaravan { goal_clone!(); + fn name(&self) -> &'static str { + "LlamaFollowCaravanGoal" + } fn flags(&self) -> u8 { super::goals::MOVE } @@ -158,7 +159,8 @@ impl Goal for FollowCaravan { } fn stop(&mut self, m: &mut Mob, _: &mut Cx) { m.extra.ints[1] = 0; - self.speed = self.base_speed; + // A double 2.1 here, while the llama built it with 2.1F. + self.speed = 2.1; } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { let caravan = head_of(m); @@ -265,7 +267,7 @@ pub fn trader_llama_tick(m: &mut Mob, w: &MobWorld) { } m.extra.ints[0] = trader.unwrap_or(m.extra.ints[0]) - 1; if m.extra.ints[0] <= 0 { - m.extra.leash = None; + super::leash::remove(m); m.removed = true; } } diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index e4637bb0c..e73e9d0ad 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -88,6 +88,8 @@ pub enum LookKind { SmoothSwimming(f32), /// Look controls that never reset pitch (e.g. ghasts keep their own). Fixed, + /// `HappyGhast.HappyGhastLookControl`. + HappyGhast, } #[derive(Clone, Debug, Default)] pub struct LookControl { @@ -307,8 +309,12 @@ impl Mob { /// LookControl.tick (and SmoothSwimmingLookControl). pub fn look_control_tick(&mut self) { let look = self.ai.look.clone(); + if look.kind == LookKind::HappyGhast { + return super::happy_ghast::look_control(self); + } let (x_d, y_d) = self.look_angles(look.wanted); match look.kind { + LookKind::HappyGhast => {} LookKind::SmoothSwimming(max) => { if look.cooldown > 0 { self.ai.look.cooldown -= 1; diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 1a9252ddb..4dcd401c1 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -174,6 +174,13 @@ impl GoalSelector { // --- random positions (DefaultRandomPos / LandRandomPos / RandomPos) ------- +/// `Mob.isWithinHome(BlockPos)`. +pub fn within_home(c: [i32; 3], r: i32, p: [i32; 3]) -> bool { + let d = |i: usize| i64::from(c[i] - p[i]); + let r = i64::from(r); + d(0) * d(0) + d(1) * d(1) + d(2) * d(2) < r * r +} + impl Mob { /// PathfinderMob.getWalkTargetValue. pub fn walk_target_value(&self, w: &MobWorld, p: [i32; 3]) -> f32 { @@ -209,17 +216,52 @@ impl Mob { let yt = self.random.next_int_bound(2 * v + 1).unwrap_or(0) - v + fly_height; Some([xt.floor() as i32, yt, zt.floor() as i32]) } - /// RandomPos.generateRandomPosTowardDirection (no home restriction). - fn toward(&mut self, _h: f64, d: [i32; 3]) -> [i32; 3] { + /// RandomPos.generateRandomPosTowardDirection: a mob with a home leans + /// half the distance back toward it. + fn toward(&mut self, h: f64, d: [i32; 3]) -> [i32; 3] { + let (mut xt, mut zt) = (f64::from(d[0]), f64::from(d[2])); + if let Some((c, _)) = self.ai.home + && h > 1.0 + { + if self.position.x > f64::from(c[0]) { + xt -= self.random.next_double() * h / 2.0; + } else { + xt += self.random.next_double() * h / 2.0; + } + if self.position.z > f64::from(c[2]) { + zt -= self.random.next_double() * h / 2.0; + } else { + zt += self.random.next_double() * h / 2.0; + } + } [ - (f64::from(d[0]) + self.position.x).floor() as i32, + (xt + self.position.x).floor() as i32, (f64::from(d[1]) + self.position.y).floor() as i32, - (f64::from(d[2]) + self.position.z).floor() as i32, + (zt + self.position.z).floor() as i32, ] } - fn default_check(&self, w: &MobWorld, p: [i32; 3]) -> bool { + /// `GoalUtils.isRestricted(mobRestricted(mob, h), mob, pos)`: a mob + /// near its home keeps the positions it picks within it. + pub fn restricted(&self, h: f64, p: [i32; 3]) -> bool { + let Some((c, r)) = self.ai.home else { + return false; + }; + let near = { + let d = |i: usize, v: f64| f64::from(c[i]) + 0.5 - v; + let (x, y, z) = ( + d(0, self.position.x), + d(1, self.position.y), + d(2, self.position.z), + ); + let reach = f64::from(r) + h + 1.0; + x * x + y * y + z * z < reach * reach + }; + near && !within_home(c, r, p) + } + fn default_check(&self, w: &MobWorld, h: f64, p: [i32; 3]) -> bool { p[1] >= crate::chunk::MIN_Y && p[1] < 320 + && !self.restricted(h, p) && self.stable_destination(w, p) && self.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0 } @@ -252,7 +294,7 @@ impl Mob { self.pick_best(w, |m| { let d = m.random_direction(h, v); let p = m.toward(f64::from(h), d); - m.default_check(w, p).then_some(p) + m.default_check(w, f64::from(h), p).then_some(p) }) } /// DefaultRandomPos.getPosAway @@ -275,7 +317,7 @@ impl Mob { std::f64::consts::FRAC_PI_2, )?; let p = m.toward(f64::from(h), d); - m.default_check(w, p).then_some(p) + m.default_check(w, f64::from(h), p).then_some(p) }) } /// DefaultRandomPos.getPosTowards @@ -291,7 +333,7 @@ impl Mob { self.pick_best(w, |m| { let d = m.random_direction_within(0.0, f64::from(h), v, 0, xd, zd, max_rad)?; let p = m.toward(f64::from(h), d); - m.default_check(w, p).then_some(p) + m.default_check(w, f64::from(h), p).then_some(p) }) } fn land_up_out_of_solid(&self, w: &MobWorld, mut p: [i32; 3]) -> Option<[i32; 3]> { @@ -304,12 +346,64 @@ 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) } + /// `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]> { + 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, + )?; + let mut p = m.toward(f64::from(h), d); + if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || m.restricted(f64::from(h), p) { + 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| { let d = m.random_direction(h, v); let p = m.toward(f64::from(h), d); - if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !m.stable_destination(w, p) { + if p[1] < crate::chunk::MIN_Y + || p[1] >= 320 + || m.restricted(f64::from(h), p) + || !m.stable_destination(w, p) + { return None; } m.land_up_out_of_solid(w, p) @@ -371,7 +465,11 @@ impl Mob { std::f64::consts::FRAC_PI_2, )?; let p = m.toward(f64::from(h), d); - if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !m.stable_destination(w, p) { + if p[1] < crate::chunk::MIN_Y + || p[1] >= 320 + || m.restricted(f64::from(h), p) + || !m.stable_destination(w, p) + { return None; } m.land_up_out_of_solid(w, p) @@ -397,7 +495,11 @@ impl Mob { std::f64::consts::FRAC_PI_2, )?; let p = m.toward(f64::from(h), d); - if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !m.stable_destination(w, p) { + if p[1] < crate::chunk::MIN_Y + || p[1] >= 320 + || m.restricted(f64::from(h), p) + || !m.stable_destination(w, p) + { return None; } m.land_up_out_of_solid(w, p) @@ -1338,6 +1440,8 @@ pub struct AvoidEntity { /// Extra condition on the avoider (e.g. untamed cats only). pub when: Option bool>, from: Vec3, + /// The mob being avoided (`toAvoid`), when it is one. + pub found: Option, } impl AvoidEntity { pub fn new(what: Avoid, max_dist: f32, walk: f64, sprint: f64) -> Self { @@ -1348,6 +1452,7 @@ impl AvoidEntity { sprint, when: None, from: Vec3::ZERO, + found: None, } } pub fn when(mut self, f: fn(&Mob) -> bool) -> Self { @@ -1382,11 +1487,16 @@ impl Goal for AvoidEntity { Avoid::Species(list) => { let id = m.id; let y = m.position.y; - cx.w.nearby(m.position, max, move |s| { - s.id != id && list.contains(&s.species) && (s.position.y - y).abs() <= 3.0 + max - }) - .map(|s| s.position) - .next() + let hit = + cx.w.nearby(m.position, max, move |s| { + s.id != id + && list.contains(&s.species) + && (s.position.y - y).abs() <= 3.0 + max + }) + .map(|s| (s.id, s.position)) + .next(); + self.found = hit.map(|h| h.0); + hit.map(|h| h.1) } }; let Some(from) = found else { return false }; @@ -1623,11 +1733,23 @@ impl Goal for Breed { ); self.love_time += 1; if self.love_time >= reduced(60) && m.distance_sqr(p.position) < 9.0 { + // Llama.getBreedOffspring and finalizeSpawnChildFromBreeding's + // experience, from the parent's random. + let llama = super::llama::is_llama(m.species()).then(|| { + let o = super::llama::breed_offspring(m, &p); + let xp = 1 + m.random.next_int_bound(7).unwrap_or(0); + cx.events.push(MobEvent::Experience { + at: [m.position.x, m.position.y, m.position.z], + amount: xp as u32, + }); + Box::new(o) + }); m.extra.in_love = 0; m.extra.age = 6000; cx.events.push(MobEvent::Breed { parent: m.id, partner: p.id, + llama, }); } } diff --git a/crates/horizon-client/src/mobs/happy_ghast.rs b/crates/horizon-client/src/mobs/happy_ghast.rs index 463d29edf..b2b0d2c51 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}, + control::{LookKind, MoveKind, Operation}, + goals::{Cx, Float, Goal, LOOK, MOVE, goal_clone}, nav::NavKind, }; use horizon_core::{ @@ -15,7 +15,7 @@ use horizon_core::{ }; // Happy ghast state: `head` the harness, `scratch[0]` 1 once set up as a -// baby and 2 as an adult, `home` and `ints[4]` the restriction, `counter` +// baby and 2 as an adult, `ai.home` the restriction, `counter` // the end tick of the follow-an-adult range pick. pub const BABY_SCALE: f64 = 0.2375; /// `Attributes.FLYING_SPEED` and the speed `travel` uses (`* 5 / 3`). @@ -25,35 +25,41 @@ 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(); + // A new move and look control (nothing wanted) and navigation. m.ai.mov.operation = Operation::Wait; + m.ai.mov.wanted = [0.0; 3]; + m.ai.mov.speed_modifier = 0.0; + m.ai.look.wanted = [0.0; 3]; + m.ai.look.cooldown = 0; + m.extra.counter2 = 0; if baby { + m.ai.look.kind = LookKind::Default; m.ai.mov.kind = MoveKind::Flying { 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; + m.ai.look.kind = LookKind::HappyGhast; let g = &mut m.ai.goals; - g.add(3, Float); + g.add(3, HappyGhastFloat); g.add(4, GhastTempt::default()); g.add(5, FloatAround { blocks: 16 }); } @@ -74,8 +80,10 @@ fn restriction_radius(m: &Mob) -> i32 { } /// `Mob.isWithinHome` for the ghast's restriction. fn within_home(m: &Mob, p: Vec3) -> bool { - let Some(h) = m.extra.home else { return true }; - let r = f64::from(m.extra.ints[4]); + let Some((h, r)) = m.ai.home else { + return true; + }; + let r = f64::from(r); let (dx, dy, dz) = ( f64::from(h[0]) + 0.5 - p.x, f64::from(h[1]) + 0.5 - p.y, @@ -83,58 +91,233 @@ fn within_home(m: &Mob, p: Vec3) -> bool { ); dx * dx + dy * dy + dz * dz < r * r } -/// `Ghast.GhastMoveControl` with the careful block checks: a push toward -/// the wanted point every few ticks while the way is clear. +/// `isOnStillTimeout`: a player standing on it (or just off it) holds it +/// still (`serverStillTimeout`, kept in `counter`). +pub fn on_still_timeout(m: &Mob) -> bool { + !m.is_baby() && m.extra.counter > 0 +} +/// `Mob.stopInPlace`. +fn stop_in_place(m: &mut Mob) { + m.ai.nav.stop(); + m.ai.xxa = 0.0; + m.ai.yya = 0.0; + m.ai.zza = 0.0; + m.ai.speed = 0.0; + m.velocity = Vec3::ZERO; +} +/// `Ghast.GhastMoveControl(careful)`: held still on a still timeout, else +/// a push toward the wanted point every 2 to 6 ticks while the way there +/// is clear. pub fn move_control(m: &mut Mob, w: &MobWorld) { + if on_still_timeout(m) { + m.ai.mov.operation = Operation::Wait; + stop_in_place(m); + } if m.ai.mov.operation != Operation::MoveTo { return; } + // floatDuration-- <= 0 + let duration = m.extra.counter2; m.extra.counter2 -= 1; - if m.extra.counter2 > 0 { + if duration > 0 { return; } m.extra.counter2 += m.random.next_int_bound(5).unwrap_or(0) + 2; let [wx, wy, wz] = m.ai.mov.wanted; let travel = Vec3::new(wx - m.position.x, wy - m.position.y, wz - m.position.z); - let len = travel.length(); - if len < 1.0e-6 { - return; - } - let b = m.bounds(); - let steps = len.ceil() as i32; - let clear = (1..=steps).all(|i| { - let f = f64::from(i) / f64::from(steps); - let d = Vec3::new(travel.x * f, travel.y * f, travel.z * f); - let at = Aabb::new( - b.min_position().add_vector(d), - b.max_position().add_vector(d), - ); - w.no_collision(at) && !touches_fluid(w, at) - }); - if clear { - let speed = AIR_SPEED; - m.velocity = m.velocity.add_vector(Vec3::new( - travel.x / len * f64::from(speed), - travel.y / len * f64::from(speed), - travel.z / len * f64::from(speed), - )); + if can_reach(m, w, travel) { + // travel.normalize().scale(FLYING_SPEED * 5 / 3) + let len = (travel.x * travel.x + travel.y * travel.y + travel.z * travel.z).sqrt(); + let unit = if len < f64::from(1.0e-5_f32) { + Vec3::ZERO + } else { + Vec3::new(travel.x / len, travel.y / len, travel.z / len) + }; + let speed = FLYING_SPEED * 5.0 / 3.0; + m.velocity = + m.velocity + .add_vector(Vec3::new(unit.x * speed, unit.y * speed, unit.z * speed)); } else { m.ai.mov.operation = Operation::Wait; } } -/// A careful ghast does not float into water or lava. -fn touches_fluid(w: &MobWorld, b: Aabb) -> bool { - let (lo, hi) = (b.min_position(), b.max_position()); +/// `EntityDimensions.makeBoundingBox` at another position. +fn bounds_at(m: &Mob, p: Vec3) -> Aabb { + let half = f64::from(m.width()) / 2.0; + let h = f64::from(m.height()); + Aabb::new( + Vec3::new(p.x - half, p.y, p.z - half), + Vec3::new(p.x + half, p.y + h, p.z + half), + ) +} +/// `GhastMoveControl.canReach`: every block around the destination box can +/// be crossed, and so can every block the box sweeps through on the way. +fn can_reach(m: &Mob, w: &MobWorld, travel: Vec3) -> bool { + let aabb = m.bounds(); + let dest = aabb.move_by(travel); + let around = dest.inflate(Vec3::new(1.0, 1.0, 1.0)); + let (lo, hi) = (around.min_position(), around.max_position()); for x in lo.x.floor() as i32..=hi.x.floor() as i32 { for y in lo.y.floor() as i32..=hi.y.floor() as i32 { for z in lo.z.floor() as i32..=hi.z.floor() as i32 { - if w.fluid(x, y, z) != crate::blocks::Fluid::None { - return true; + if !traversal_possible(m, w, None, [x, y, z], false, false) { + return false; } } } } - false + let (water, lava) = (m.fluids.in_water, m.fluids.in_lava); + let start = m.position; + let end = start.add_vector(travel); + horizon_core::geometry::sweep_intersected_blocks(start, end, dest, 1 << 22, |p, _| { + let at = [p.x, p.y, p.z]; + let unit = Aabb::new( + Vec3::new(f64::from(at[0]), f64::from(at[1]), f64::from(at[2])), + Vec3::new( + f64::from(at[0]) + 1.0, + f64::from(at[1]) + 1.0, + f64::from(at[2]) + 1.0, + ), + ); + aabb.intersects(unit) || traversal_possible(m, w, Some((start, end)), at, water, lava) + }) + .unwrap_or(false) +} +/// `GhastMoveControl.blockTraversalPossible` for a careful ghast: air, or no +/// collision (along the way when `along` is given), never a +/// `#happy_ghast_avoids` block, and a fluid only where the ghast already is. +fn traversal_possible( + m: &Mob, + w: &MobWorld, + along: Option<(Vec3, Vec3)>, + p: [i32; 3], + through_water: bool, + through_lava: bool, +) -> bool { + let state = w.world.block(p[0], p[1], p[2]); + if w.facts.is_air(state) { + return true; + } + let boxes = w.block_collision_boxes(p[0], p[1], p[2]); + let no_collisions = match along { + Some((from, to)) => !bounds_at(m, from).collided_along_vector(to.subtract(from), &boxes), + None => boxes.is_empty(), + }; + if w.has_tag( + "minecraft:happy_ghast_avoids", + w.block_name(p[0], p[1], p[2]), + ) { + return false; + } + let (fluid, height) = w.fluid_height(p[0], p[1], p[2]); + if fluid != crate::blocks::Fluid::None { + let collided = match along { + None => true, + // collidedWithFluid: the fluid's own height. + Some((from, to)) => { + let fluid_box = Aabb::new( + Vec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2])), + Vec3::new( + f64::from(p[0]) + 1.0, + f64::from(p[1]) + height, + f64::from(p[2]) + 1.0, + ), + ); + bounds_at(m, from).collided_along_vector(to.subtract(from), &[fluid_box]) + } + }; + if collided { + return match fluid { + crate::blocks::Fluid::Water => through_water, + _ => through_lava, + }; + } + } + no_collisions +} +/// `HappyGhast.HappyGhastLookControl`: square to the world on a still +/// timeout, face what it looks at, else face its motion +/// (`Ghast.faceMovementDirection`). +pub fn look_control(m: &mut Mob) { + use horizon_core::geometry::trig; + let to_deg = 180.0_f32 / std::f32::consts::PI; + if on_still_timeout(m) { + // Mth.wrapDegrees90 + let mut close = m.yaw % 90.0; + if close >= 45.0 { + close -= 90.0; + } + if close < -45.0 { + close += 90.0; + } + m.yaw -= close; + m.head_yaw = m.yaw; + } else if m.ai.look.cooldown > 0 { + m.ai.look.cooldown -= 1; + let [wx, _, wz] = m.ai.look.wanted; + m.yaw = -(trig::atan2(wx - m.position.x, wz - m.position.z) as f32) * to_deg; + m.body_yaw = m.yaw; + m.head_yaw = m.body_yaw; + } else if m.ai.target.is_none() { + let v = m.velocity; + m.yaw = -(trig::atan2(v.x, v.z) as f32) * to_deg; + m.body_yaw = m.yaw; + } +} +/// `HappyGhast.tick`'s still timeout: it runs out (after the first three +/// seconds) unless a player stands on top (`scanPlayerAboveGhast`). +pub fn still_tick(m: &mut Mob, w: &MobWorld) { + if m.is_baby() { + m.extra.counter = 0; + return; + } + if m.extra.counter > 0 && m.age > 60 { + m.extra.counter -= 1; + } + if player_above(m, w) { + m.extra.counter = 10; + } +} +/// `scanPlayerAboveGhast`: a player (not one riding a happy ghast) within +/// a block around the top, up to half the ghast's height above it. +pub fn player_above(m: &Mob, w: &MobWorld) -> bool { + let Some(p) = w.player.as_ref().filter(|p| !p.spectator) else { + return false; + }; + if m.rider.is_some() { + return false; + } + let b = m.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + let area = Aabb::new( + Vec3::new(lo.x - 1.0, hi.y - f64::from(1.0e-5_f32), lo.z - 1.0), + Vec3::new(hi.x + 1.0, hi.y + (hi.y - lo.y) / 2.0, hi.z + 1.0), + ); + area.contains(p.position) +} +/// `HappyGhastFloatGoal`: a `FloatGoal` off a still timeout. +#[derive(Clone, Debug)] +struct HappyGhastFloat; +impl Goal for HappyGhastFloat { + goal_clone!(); + fn name(&self) -> &'static str { + "HappyGhastFloatGoal" + } + fn flags(&self) -> u8 { + Float.flags() + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + !on_still_timeout(m) && Float.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + Float.can_use(m, cx) + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + Float.tick(m, cx) + } } /// `TemptGoal.ForNonPathfinders`: drift toward a player holding food, or /// food and harnesses for a bare adult. @@ -151,6 +334,9 @@ impl GhastTempt { } impl Goal for GhastTempt { goal_clone!(); + fn name(&self) -> &'static str { + "ForNonPathfinders" + } fn flags(&self) -> u8 { MOVE | LOOK } @@ -160,22 +346,24 @@ impl Goal for GhastTempt { return false; } let Some(p) = &cx.w.player else { return false }; - // Attributes.TEMPT_RANGE 16. + // getNearestPlayer(TargetingConditions.forNonCombat() + // .ignoreLineOfSight().range(TEMPT_RANGE 16)): creative players too. + let visibility = if p.sneaking { 0.8 } else { 1.0 }; + let range = (16.0_f64 * visibility).max(2.0); p.alive - && !p.creative + && !p.spectator && (Self::wants(m, &p.main_hand) || Self::wants(m, &p.off_hand)) - && m.distance_sqr(p.position) <= 256.0 + && m.distance_sqr(p.position) <= range * range } fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + // stopNavigation: setWait; calmDown = reducedTickDelay(100). m.ai.mov.operation = Operation::Wait; - self.calm_down = 50; - } - fn every_tick(&self) -> bool { - true + self.calm_down = super::goals::reduced(100); } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { let Some(p) = cx.w.player.clone() else { return }; m.look_at(p.eye); + // stopDistance 7. if m.distance_sqr(p.position) < 49.0 { m.ai.mov.operation = Operation::Wait; } else { @@ -227,6 +415,9 @@ impl FloatAround { } impl Goal for FloatAround { goal_clone!(); + fn name(&self) -> &'static str { + "RandomFloatAroundGoal" + } fn flags(&self) -> u8 { MOVE } @@ -242,85 +433,39 @@ impl Goal for FloatAround { fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool { false } + /// `getSuitableFlyToPosition`: the first of 64 random points within 16 + /// blocks (and home) that is good; failing that, the last point, kept + /// below the motion-blocking surface. fn start(&mut self, m: &mut Mob, cx: &mut Cx) { let c = m.position; - let mut result: Option = None; - for _ in 0..64 { - let r = &mut m.random; - let t = Vec3::new( - c.x + f64::from(r.next_float() * 2.0 - 1.0) * 16.0, - c.y + f64::from(r.next_float() * 2.0 - 1.0) * 16.0, - c.z + f64::from(r.next_float() * 2.0 - 1.0) * 16.0, - ); - result = Some(t); - if within_home(m, t) && self.good(cx.w, t) { - break; - } - result = None; - } - let mut t = result.unwrap_or_else(|| { + let choose = |m: &mut Mob| { let r = &mut m.random; Vec3::new( - c.x + f64::from(r.next_float() * 2.0 - 1.0) * 16.0, - c.y + f64::from(r.next_float() * 2.0 - 1.0) * 16.0, - c.z + f64::from(r.next_float() * 2.0 - 1.0) * 16.0, + c.x + f64::from((r.next_float() * 2.0 - 1.0) * 16.0), + c.y + f64::from((r.next_float() * 2.0 - 1.0) * 16.0), + c.z + f64::from((r.next_float() * 2.0 - 1.0) * 16.0), ) - }); + }; + let mut result: Option = None; + for _ in 0..64 { + let t = choose(m); + result = within_home(m, t).then_some(t); + if let Some(t) = result + && self.good(cx.w, t) + { + m.ai.mov.set_wanted(t.x, t.y, t.z, 1.0); + return; + } + } + let mut t = result.unwrap_or_else(|| choose(m)); let top = cx.w.motion_blocking_height(t.x.floor() as i32, t.z.floor() as i32); if top < t.y.floor() as i32 && top > crate::chunk::MIN_Y { - t.y = c.y - (c.y - t.y).abs(); + t.y = m.position.y - (m.position.y - t.y).abs(); } 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 }; @@ -351,13 +496,17 @@ pub fn ridden(m: &mut Mob) { m.ai.zza = forward * scale; m.ai.mov.operation = Operation::Wait; } -/// `HappyGhast.aiStep`, `tick` and `checkRestriction`: the adult/baby -/// setup at the age boundary, the home, face-the-motion and slow healing. -pub fn ai_step(m: &mut Mob, w: &MobWorld) { +/// The adult or ghastling setup for its age (`ageBoundaryReached`). +pub fn ensure_setup(m: &mut Mob) { let baby = m.is_baby(); if m.extra.scratch[0] != if baby { 1 } else { 2 } { setup(m, baby); } +} +/// `HappyGhast.aiStep`, `tick` and `checkRestriction`: the adult/baby +/// setup at the age boundary, the home, face-the-motion and slow healing. +pub fn ai_step(m: &mut Mob, w: &MobWorld) { + ensure_setup(m); // checkRestriction. if m.extra.leash.is_none() && m.rider.is_none() { let radius = restriction_radius(m); @@ -366,26 +515,17 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld) { m.position.y.floor() as i32, m.position.z.floor() as i32, ]; - let stale = match m.extra.home { - Some(h) => { + // !hasHome || !home.closerThan(blockPosition, radius + 16) || radius changed + let stale = match m.ai.home { + Some((h, r)) => { (h[0] - here[0]).pow(2) + (h[1] - here[1]).pow(2) + (h[2] - here[2]).pow(2) >= (radius + 16).pow(2) - || radius != m.extra.ints[4] + || radius != r } None => true, }; if stale { - m.extra.home = Some(here); - m.extra.ints[4] = radius; - } - } - // LookControl: face where it is going. - if !baby && m.rider.is_none() { - let v = m.velocity; - if m.ai.target.is_none() && v.x * v.x + v.z * v.z > 1.0e-6 { - m.yaw = -(v.x.atan2(v.z) as f32).to_degrees(); - m.body_yaw = m.yaw; - m.head_yaw = m.yaw; + m.ai.home = Some((here, radius)); } } // continuousHeal: a point every 30 seconds, every second in rain. @@ -401,6 +541,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld) { m.health = (m.health + 1.0).min(m.attrs.max_health); } } + still_tick(m, w); } /// Sounds: the ghastling has its own. pub fn sounds(m: &Mob) -> [&'static str; 3] { diff --git a/crates/horizon-client/src/mobs/leash.rs b/crates/horizon-client/src/mobs/leash.rs index cc48bc4d8..b7c5011ba 100644 --- a/crates/horizon-client/src/mobs/leash.rs +++ b/crates/horizon-client/src/mobs/leash.rs @@ -209,6 +209,21 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } return; }; + // PathfinderMob.whenLeashedTo: home is the holder's block, within the + // elastic distance less one. + let elastic = if m.species() == super::Species::HappyGhast { + 10.0 + } else { + ELASTIC + }; + m.ai.home = Some(( + [ + state.position.x.floor() as i32, + state.position.y.floor() as i32, + state.position.z.floor() as i32, + ], + elastic as i32 - 1, + )); let b = m.bounds(); let (lo, hi) = (b.min_position(), b.max_position()); let center = Vec3::new( @@ -265,6 +280,14 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { }; m.extra.leash_spin *= friction; } +/// The lead comes off (`Mob.onLeashRemoved`): no more home. +pub fn remove(m: &mut Mob) -> Option { + let was = m.extra.leash.take(); + if was.is_some() { + m.ai.home = None; + } + was +} /// `PathfinderMob.closeRangeLeashBehaviour`: walk to within two blocks of /// the holder unless panicking. fn close_range(m: &mut Mob, w: &MobWorld, holder: &HolderState) { diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index c770f16df..03d2f201f 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -116,6 +116,22 @@ impl MobWorld<'_> { } out } + /// `BlockState.getCollisionShape(level, pos)` (the empty collision + /// context) as boxes in the world. + pub fn block_collision_boxes(&self, x: i32, y: i32, z: i32) -> Vec { + let mut scene = SceneCollisions { + world: self.world, + binding: self.collision, + }; + let state = self.world.block(x, y, z); + let at = horizon_core::position::BlockPos::new(x, y, z); + let context = horizon_world::collision_context::CollisionContext::empty(false); + let offset = Vec3::new(f64::from(x), f64::from(y), f64::from(z)); + self.collision + .collision_shape_with_context(&mut scene, state, at, &context) + .map(|shape| shape.boxes().iter().map(|b| b.move_by(offset)).collect()) + .unwrap_or_default() + } pub fn no_collision(&self, b: Aabb) -> bool { let mut scene = SceneCollisions { world: self.world, @@ -125,6 +141,38 @@ impl MobWorld<'_> { } } impl Mob { + /// `Entity.refreshDimensions` after growing from `old_w` by `old_h`: + /// `fudgePositionAfterSizeChange` moves the mob to the free spot nearest + /// its old centre where the bigger box fits (`findFreePosition`), or + /// failing that, one that fits at the old height. + pub fn fudge_position_after_size_change(&mut self, w: &MobWorld, old_w: f64, old_h: f64) { + let (new_w, new_h, _) = self.dims(); + let small = new_w <= 4.0 && new_h <= 4.0; + if self.age == 0 || self.no_physics() || !small || !(new_w > old_w || new_h > old_h) { + return; + } + let center = Vec3::new( + self.position.x, + self.position.y + old_h / 2.0, + self.position.z, + ); + let dw = (new_w - old_w).max(0.0) + 1.0e-6; + let dh = (new_h - old_h).max(0.0) + 1.0e-6; + let at = |allowed: Aabb, size_y: f64| free_position(w, allowed, center, new_w, size_y); + if let Some(p) = at(Aabb::of_size(center, Vec3::new(dw, dh, dw)), new_h) { + self.position = Vec3::new(p.x, p.y - new_h / 2.0, p.z); + return; + } + if new_w > old_w + && new_h > old_h + && let Some(p) = at(Aabb::of_size(center, Vec3::new(dw, 1.0e-6, dw)), old_h) + { + self.position = Vec3::new(p.x, p.y - old_h / 2.0 + 1.0e-6, p.z); + } + } + fn no_physics(&self) -> bool { + false + } pub fn eye_y(&self) -> f64 { self.position.y + self.eye_height() } @@ -417,14 +465,21 @@ impl Mob { self.travel_in_air(w, input, events); } } - /// LivingEntity.travelFlying (ghast 0.02, phantom 0.2): no gravity, 0.91 drag. + /// LivingEntity.travelFlying: no gravity, `0.91F` drag in the air, + /// `0.8F` in water and 0.5 in lava. A happy ghast swims as fast as it + /// flies (`HappyGhast.travel`); the others at 0.02. fn travel_flying(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec) { - let (speed, drag) = if self.fluids.in_water { - (0.02, 0.8) - } else if self.fluids.in_lava { - (0.02, 0.5) + let fluid_speed = if self.species() == super::Species::HappyGhast { + self.kind.air_speed } else { - (self.kind.air_speed, 0.91) + 0.02 + }; + let (speed, drag) = if self.fluids.in_water { + (fluid_speed, f64::from(0.8_f32)) + } else if self.fluids.in_lava { + (fluid_speed, 0.5) + } else { + (self.kind.air_speed, f64::from(0.91_f32)) }; self.move_relative(speed, input); self.do_move(w, events); @@ -638,3 +693,44 @@ fn fluid_falling(gravity: f64, falling: bool, m: Vec3) -> Vec3 { m } } + +/// `CollisionGetter.findFreePosition`: within `allowed`, the point nearest +/// `preferred` at which a box of the size, centred there, meets no block. +fn free_position( + w: &MobWorld, + allowed: Aabb, + preferred: Vec3, + size_x: f64, + size_y: f64, +) -> Option { + use horizon_core::geometry::{ShapeOp, VoxelShape}; + let allowed_shape = VoxelShape::from_box(allowed).ok()?; + if allowed_shape.is_empty() { + return None; + } + let half = Vec3::new(size_x / 2.0, size_y / 2.0, size_x / 2.0); + let area = allowed.inflate(half); + let (lo, hi) = (area.min_position(), area.max_position()); + let mut collisions = VoxelShape::empty(); + // getBlockCollisions: the block shapes that reach into the area. + for x in (lo.x - 1.0e-7).floor() as i32 - 1..=(hi.x + 1.0e-7).floor() as i32 + 1 { + for y in (lo.y - 1.0e-7).floor() as i32 - 1..=(hi.y + 1.0e-7).floor() as i32 + 1 { + for z in (lo.z - 1.0e-7).floor() as i32 - 1..=(hi.z + 1.0e-7).floor() as i32 + 1 { + let boxes = w.block_collision_boxes(x, y, z); + let touches = boxes.iter().any(|b| { + let (a, c) = (b.min_position(), b.max_position()); + a.x < hi.x && c.x > lo.x && a.y < hi.y && c.y > lo.y && a.z < hi.z && c.z > lo.z + }); + if !touches { + continue; + } + for b in boxes { + let grown = VoxelShape::from_box(b.inflate(half)).ok()?; + collisions = collisions.join(&grown, ShapeOp::OR).ok()?; + } + } + } + } + let free = allowed_shape.join(&collisions, ShapeOp::ONLY_FIRST).ok()?; + free.closest_point(preferred) +} diff --git a/crates/horizon-client/src/mobs/llama.rs b/crates/horizon-client/src/mobs/llama.rs index 82aeebe17..b91dc5bfa 100644 --- a/crates/horizon-client/src/mobs/llama.rs +++ b/crates/horizon-client/src/mobs/llama.rs @@ -3,9 +3,7 @@ //! spit ranged attack, hunting wolves (and, for traders, zombies and //! illagers) and `LlamaModel`. use super::{ - Mob, MobEvent, MobWorld, Seen, Species, Who, - anim::{Poses, State}, - equine, + Mob, MobEvent, MobWorld, Seen, Species, Who, equine, goals::{ Breed, Cx, Float, FollowParent, Goal, HurtByTarget, LookAtPlayer, NearestTarget, Panic, Prey, RandomLookAround, Stroll, Tempt, goal_clone, @@ -14,7 +12,6 @@ use super::{ }; use crate::projectiles::{Projectile, ProjectileKind}; use horizon_core::{geometry::Vec3, random::RandomSource}; -use std::f32::consts::PI; pub const VARIANTS: [&str; 4] = ["creamy", "white", "brown", "gray"]; /// `Llama.getMaxTemper`. @@ -29,9 +26,10 @@ pub fn is_llama(s: Species) -> bool { pub fn is_trader(m: &Mob) -> bool { m.species() == Species::TraderLlama } -/// `Llama.getStrength`. +/// `Llama.getStrength`: the stored strength (0 for a llama that was never +/// given one; `setStrength` keeps it within 1 to 5). pub fn strength(m: &Mob) -> i32 { - i32::from(m.extra.variant2).clamp(1, 5) + i32::from(m.extra.variant2) } /// `getInventoryColumns`: a chest holds three rows of `strength` columns. pub fn inventory_columns(m: &Mob) -> i32 { @@ -64,7 +62,7 @@ pub fn register(m: &mut Mob) { g.add(1, Panic::new(2.0)); } g.add(1, equine::RunAroundLikeCrazy); - g.add(2, super::caravan::FollowCaravan::new(2.1)); + g.add(2, super::caravan::FollowCaravan::new(f64::from(2.1_f32))); g.add(3, RangedAttack::new(1.25, 40, 40, 20.0, spit)); g.add(3, Panic::new(1.2)); g.add(4, Breed::new(1.0)); @@ -129,6 +127,59 @@ pub fn offspring(child: &mut Mob, a: &Mob, b: &Mob, r: &mut impl RandomSource) { child.persistent = true; } } +/// A llama's baby as `Llama.getBreedOffspring` makes it. +#[derive(Clone, Debug)] +pub struct Offspring { + pub max_health: f32, + pub jump: f64, + pub speed: f64, + pub strength: u8, + pub variant: u8, +} +/// `Llama.getBreedOffspring` with `AbstractHorse.setOffspringAttributes`, +/// drawn from the parent's random with the partner's stock. +pub fn breed_offspring(m: &mut Mob, partner: &Seen) -> Offspring { + // Seen.profession is the partner's strength. + let top = strength(m).max(i32::from(partner.profession)); + let (health, jump, speed, own) = ( + f64::from(m.attrs.max_health), + m.extra.vector[0], + m.attrs.speed, + m.extra.variant, + ); + let r = &mut m.random; + let max_health = equine::offspring(health, partner.stats[0], 15.0, 30.0, r) as f32; + let jump = equine::offspring(jump, partner.stats[1], 0.4, 1.0, r); + let speed = equine::offspring(speed, partner.stats[2], 0.1125, 0.3375, r); + let mut s = r.next_int_bound(top).unwrap_or(0) + 1; + if r.next_float() < 0.03 { + s += 1; + } + let variant = if r.next_boolean() { + own + } else { + partner.variant + }; + Offspring { + max_health, + jump, + speed, + strength: s.clamp(1, 5) as u8, + variant, + } +} +/// The game makes the baby drawn by `breed_offspring`. +pub fn apply_offspring(child: &mut Mob, o: &Offspring) { + child.attrs.max_health = o.max_health; + child.health = o.max_health; + child.extra.vector[0] = o.jump; + child.attrs.speed = o.speed; + child.extra.variant2 = o.strength; + child.extra.variant = o.variant; + if is_trader(child) { + child.persistent = true; + } +} /// `LlamaHurtByTargetGoal`: stops hunting right after a spit. #[derive(Clone, Debug)] struct LlamaHurtBy(HurtByTarget); @@ -255,17 +306,6 @@ pub fn decor(m: &Mob) -> Option<(String, String)> { (model.into(), format!("entity/equipment/llama_body/{name}")) }) } -/// `LlamaModel.setupAnim`. -pub fn anim(m: &Mob, s: &State, p: &mut Poses) { - super::anim::quadruped(p, s); - let chest = m.extra.chested && !s.baby; - for part in ["right_chest", "left_chest"] { - if !chest { - p.visible(part, false); - } - } - let _ = PI; -} #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client/src/mobs/sniffer.rs b/crates/horizon-client/src/mobs/sniffer.rs index e8049b2d3..6979171b8 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) { @@ -540,14 +104,7 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { 1.0, )); } - if current == SEARCHING && m.age.is_multiple_of(20) { - events.push(MobEvent::Sound( - "entity.sniffer.searching", - m.center(), - 1.0, - 1.0, - )); - } + // The searching sound is the client's (`playSearchingSound`). // onPathfindingStart / Done: water only blocks the way while it is dry. let wet = m.fluids.in_water || m.fire_ticks > 0; m.set_malus(PathType::Water, if wet { 0.0 } else { -1.0 }); diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index c00706b89..4e5e3d290 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -65,7 +65,7 @@ pub fn register(m: &mut Mob) { g.add(1, Float); g.add(1, TamePanic(Panic::new(1.5))); g.add(2, SitWhenOrdered); - g.add(3, AvoidLlamas); + g.add(3, AvoidLlamas::new()); g.add(4, LeapAtTarget::new(0.4)); g.add(5, MeleeAttack::new(1.0, true)); g.add(6, FollowOwner::new(1.0, 10.0, 2.0)); @@ -255,38 +255,56 @@ impl Goal for SitWhenOrdered { } /// `Wolf.WolfAvoidEntityGoal`: untamed wolves flee llamas. #[derive(Clone, Debug)] -struct AvoidLlamas; +struct AvoidLlamas(super::goals::AvoidEntity); +impl AvoidLlamas { + fn new() -> Self { + Self(super::goals::AvoidEntity::new( + super::goals::Avoid::Species(vec![Species::Llama, Species::TraderLlama]), + 24.0, + 1.5, + 1.5, + )) + } +} +/// `Wolf.WolfAvoidEntityGoal`: a wild wolf runs from a llama, the more +/// likely the stronger it is (`strength >= random.nextInt(5)`), and drops +/// its target while it does. impl Goal for AvoidLlamas { goal_clone!(); + fn name(&self) -> &'static str { + "WolfAvoidEntityGoal" + } fn flags(&self) -> u8 { - MOVE + self.0.flags() } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - if m.extra.tame { + if !self.0.can_use(m, cx) { return false; } - let pos = m.position; - let llama = - cx.w.nearby(pos, 24.0, |s| { - matches!(s.species, Species::Llama | Species::TraderLlama) && s.alive - }) - .map(|s| s.position) - .next(); - let Some(from) = llama else { + // Seen.profession is the llama's strength (`variant2`). + let Some(strength) = self + .0 + .found + .and_then(|id| cx.w.seen(id)) + .map(|s| s.profession) + else { return false; }; - // DefaultRandomPos.getPosAway(16, 7, from). - let away = Vec3::new(pos.x - from.x, 0.0, pos.z - from.z); - let len = (away.x * away.x + away.z * away.z).sqrt().max(1e-6); - let target = [ - pos.x + away.x / len * 16.0, - pos.y, - pos.z + away.z / len * 16.0, - ]; - m.nav_move_to(cx.w, target, 1.5) + !m.extra.tame && i32::from(strength) >= m.random.next_int_bound(5).unwrap_or(0) } - fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { - !m.ai.nav.is_done() + 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) { + m.ai.target = None; + self.0.start(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx) + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + m.ai.target = None; + self.0.tick(m, cx) } } /// `FollowOwnerGoal(speed, startDistance, stopDistance)`. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java index c9e04db44..6d1fe235a 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java @@ -115,6 +115,16 @@ public final class VanillaEntityAnimOracle { else if (t == boolean.class) f.setBoolean(state, value.getAsBoolean()); else if (t.isEnum()) { for (Object c : t.getEnumConstants()) if (((Enum) c).name().equals(value.getAsString())) f.set(state, c); + } else if (t == net.minecraft.world.item.ItemStack.class) { + // value = an item id. The item components are not bound outside a level, so the stack + // carries none: models only test that it is not empty. + var item = net.minecraft.core.registries.BuiltInRegistries.ITEM.wrapAsHolder(net.minecraft.core.registries.BuiltInRegistries.ITEM.getValue( + net.minecraft.resources.Identifier.parse(value.getAsString()))); + var ctor = net.minecraft.world.item.ItemStack.class.getDeclaredConstructor(net.minecraft.core.Holder.class, int.class, + net.minecraft.core.component.PatchedDataComponentMap.class); + ctor.setAccessible(true); + f.set(state, ctor.newInstance(item, 1, new net.minecraft.core.component.PatchedDataComponentMap( + net.minecraft.core.component.DataComponentMap.EMPTY))); } else if (t.getSimpleName().equals("AnimationState")) { // value = age in ticks since start (negative = stopped) var a = (net.minecraft.world.entity.AnimationState) f.get(state); 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 75fe7d24a..f42710e2f 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -162,6 +162,8 @@ public final class VanillaMobAiOracle { /** The tick from which the player faces turnYaw (head and body), else 0. */ int turnTick = Integer.MAX_VALUE; float turnYaw; + /** What the player holds in its main hand (an item id), or null. */ + String hand; List mobs = new ArrayList<>(); long levelSeed = 0; /** Blocks placed when the scenario starts, so their block entities start afresh and tick. */ @@ -207,7 +209,8 @@ public final class VanillaMobAiOracle { String[] tv = f[i].substring(5).split(","); s.turnTick = Integer.parseInt(tv[0]); s.turnYaw = Float.parseFloat(tv[1]); - } else throw new IllegalArgumentException(line); + } else if (f[i].startsWith("hand=")) s.hand = f[i].substring(5); + else throw new IllegalArgumentException(line); } } case "mob" -> { @@ -461,6 +464,8 @@ public final class VanillaMobAiOracle { method(player.connection.getClass(), "markClientLoaded").invoke(player.connection); } player.setGameMode(s.creative ? GameType.CREATIVE : GameType.SURVIVAL); + player.setItemInHand(net.minecraft.world.InteractionHand.MAIN_HAND, s.hand == null ? net.minecraft.world.item.ItemStack.EMPTY + : new net.minecraft.world.item.ItemStack(BuiltInRegistries.ITEM.getValue(net.minecraft.resources.Identifier.parse(s.hand)))); player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F); // snapTo leaves the head and body as the player was created // (a random head yaw): face +z like the probe's player. @@ -493,6 +498,14 @@ public final class VanillaMobAiOracle { for (String flag : spec.flags) { if (flag.equals("persistent")) mob.setPersistenceRequired(); else if (flag.equals("noai")) mob.setNoAi(true); + else if (flag.equals("inlove")) ((net.minecraft.world.entity.animal.Animal) mob).setInLoveTime(600); + else if (flag.equals("tame") && mob instanceof net.minecraft.world.entity.animal.equine.AbstractHorse horse) horse.setTamed(true); + else if (flag.startsWith("age=")) ((AgeableMob) mob).setAge(Integer.parseInt(flag.substring(4))); + else if (flag.startsWith("strength=")) method(net.minecraft.world.entity.animal.equine.Llama.class, "setStrength", int.class) + .invoke(mob, Integer.parseInt(flag.substring(9))); + else if (flag.equals("leashed") || flag.startsWith("leashto=")) { + // Leashed once every mob exists (below). + } else throw new IllegalArgumentException(flag); } level.addFreshEntity(mob); @@ -506,6 +519,14 @@ public final class VanillaMobAiOracle { brains.add(brain); seeds.add(spec.seed); } + // Leads: to the player ("leashed") or to the n-th mob ("leashto=n"). + for (int i = 0; i < s.mobs.size(); i++) { + for (String flag : s.mobs.get(i).flags) { + if (flag.equals("leashed")) ((net.minecraft.world.entity.Leashable) mobs.get(i)).setLeashedTo(player, true); + else if (flag.startsWith("leashto=")) ((net.minecraft.world.entity.Leashable) mobs.get(i)) + .setLeashedTo(mobs.get(Integer.parseInt(flag.substring(8))), true); + } + } // Hearts start with the scenario: their tickers have not run during the warm-up. var blockLookup = level.holderLookup(Registries.BLOCK); List heartPositions = new ArrayList<>(); diff --git a/tools/test_entity_model_parity.py b/tools/test_entity_model_parity.py index a8d23bd33..bbc0a8074 100644 --- a/tools/test_entity_model_parity.py +++ b/tools/test_entity_model_parity.py @@ -48,6 +48,8 @@ EXTRAS = [ ('minecraft:pillager#main', 'IllagerModel'), ('minecraft:vindicator#main', 'IllagerModel'), ('minecraft:llama#main', 'LlamaModel'), ('minecraft:trader_llama#main', 'LlamaModel'), ('minecraft:llama_baby#main', 'BabyLlamaModel'), ('minecraft:trader_llama_baby#main', 'BabyLlamaModel'), + # LlamaDecorLayer: the carpet and the trader's blanket. + ('minecraft:llama#decor', 'LlamaModel'), ('minecraft:llama_baby#decor', 'BabyLlamaModel'), ('minecraft:donkey#main', 'DonkeyModel'), ('minecraft:mule#main', 'DonkeyModel'), ('minecraft:donkey_baby#main', 'BabyDonkeyModel'), ('minecraft:mule_baby#main', 'BabyDonkeyModel'), ('minecraft:skeleton_horse#main', 'HorseModel'), ('minecraft:zombie_horse#main', 'HorseModel'), @@ -138,6 +140,8 @@ PIGLIN = [{'armPose': pose, 'maxCrossbowChageDuration': 25.0, 'ticksUsingItem': EQUINE = [{'eatAnimation': 0.6}, {'standAnimation': 0.5}, {'eatAnimation': 0.3, 'standAnimation': 0.4, 'feedingAnimation': 0.7}, {'isInWater': T}, {'standAnimation': 1.0, 'eatAnimation': 1.0}] WATER = [{'isInWater': T}, {'isInWater': F}] +GHAST_BODY = [{'bodyItem': 'minecraft:white_harness'}, {'isRidden': T}, {'bodyItem': 'minecraft:red_harness', 'isRidden': T}, + {'isLeashHolder': T, 'bodyItem': 'minecraft:blue_harness'}] SPECIES = { 'horse': EQUINE, 'donkey': EQUINE + [{'hasChest': T}], 'mule': EQUINE + [{'hasChest': T}], 'zombie_horse': EQUINE, 'skeleton_horse': EQUINE, 'iron_golem': [{'attackTicksRemaining': 7.0}, {'offerFlowerTick': 30}, {'attackTicksRemaining': 0.0, 'offerFlowerTick': 0}], @@ -176,6 +180,11 @@ SPECIES = { {'sitAmount': 0.6, 'isEating': T}, {'sitAmount': 1.0, 'isScared': T}, {'sitAmount': 0.3}, {'lieOnBackAmount': 0.5}, {'rollAmount': 0.7}], 'llama': [{'hasChest': T}, {'hasChest': F}], + 'sniffer': [{'isSearching': T}, {'diggingAnimationState': 2}, {'sniffingAnimationState': 5}, {'risingAnimationState': 1}, + {'feelingHappyAnimationState': 3}, {'scentingAnimationState': 0}, {'diggingAnimationState': 50, 'isSearching': T}, + {'feelingHappyAnimationState': 30, 'scentingAnimationState': 20}], + 'happy_ghast': GHAST_BODY, 'happy_ghast_ropes': GHAST_BODY, 'happy_ghast_baby_ropes': GHAST_BODY, + 'happy_ghast_harness': GHAST_BODY, 'happy_ghast_baby_harness': GHAST_BODY, 'trader_llama': [{'hasChest': T}, {'hasChest': F}], 'turtle': [{'isOnLand': T}, {'isOnLand': T, 'isLayingEgg': T}, {'isOnLand': F, 'hasEgg': T}, {'isOnLand': T, 'hasEgg': T}], 'strider': [{'isRidden': T}, {'isRidden': F}], diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index d3a19f9a3..baef29675 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -98,6 +98,52 @@ def scenarios(): add('heart_hurt', 260, TRUNK + ['heart 3 -59 3 minecraft:creaking_heart[axis=y,creaking_heart_state=awake,natural=true]', 'player 0.5 -60 -6.5', 'hurt 60 0', 'hurt 64 0', 'hurt 200 0'], 'time=18000 spawning') add('heart_far', 120, TRUNK + ['heart 3 -59 3 minecraft:creaking_heart[axis=y,creaking_heart_state=awake,natural=true]', 'player 40.5 -60 0.5'], 'time=18000 spawning') + # 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']) + # Breeding, temptation and growing up. + add('sniffer_love', 300, ['mob minecraft:sniffer 0.5 -60 0.5 0 91 persistent inlove', + 'mob minecraft:sniffer 4.5 -60 0.5 0 92 persistent inlove']) + add('sniffer_tempted', 200, ['player 7.5 -60 0.5 hand=minecraft:torchflower_seeds', + 'mob minecraft:sniffer 0.5 -60 0.5 0 93 persistent']) + add('llama_love', 300, ['mob minecraft:llama 0.5 -60 0.5 0 94 persistent tame inlove strength=3', + 'mob minecraft:llama 4.5 -60 0.5 0 95 persistent tame inlove strength=2']) + add('llama_tempted', 200, ['player 7.5 -60 0.5 hand=minecraft:hay_block', + 'mob minecraft:llama 0.5 -60 0.5 0 96 persistent']) + add('ghastling_tempted', 200, ['player 8.5 -60 0.5 hand=minecraft:snowball', + 'mob minecraft:happy_ghast 0.5 -57 0.5 0 97 persistent baby']) + add('happy_ghast_tempted', 200, ['player 12.5 -60 0.5 hand=minecraft:snowball', + 'mob minecraft:happy_ghast 0.5 -55 0.5 0 98 persistent']) + add('ghastling_grows', 200, ['player 8.5 -60 0.5', + 'mob minecraft:happy_ghast 0.5 -57 0.5 0 99 persistent age=-40']) + # Llama caravans: two llamas fall in behind one on the player's lead; a wandering trader's two + # llamas on its leads. + add('llama_caravan', 300, ['player 0.5 -60 0.5', + 'mob minecraft:llama 3.5 -60 0.5 0 101 persistent leashed strength=3', + 'mob minecraft:llama 9.5 -60 2.5 0 102 persistent strength=2', + 'mob minecraft:llama 13.5 -60 -1.5 0 103 persistent strength=1']) + add('trader_llamas', 300, ['player 14.5 -60 0.5', + 'mob minecraft:wandering_trader 0.5 -60 0.5 0 104 persistent', + 'mob minecraft:trader_llama 3.5 -60 1.5 0 105 persistent leashto=0 strength=2', + 'mob minecraft:trader_llama 3.5 -60 -1.5 0 106 persistent leashto=0 strength=4']) return s