From 7c2a31206c18efc062c10edb46cdf8ceeb33fe22 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 07:57:42 +0200 Subject: [PATCH] Bees fly, pollinate flowers, get angry and sting (#208) A port of vanilla 26.3 Bee: FlyingMoveControl and flying navigation, hover wandering, flower search and pollination (nectar), growing crops, tempting and breeding, persistent anger with the hurt-by alert, the sting (poison, stinger lost, later death), drowning, staying home at night and in rain, roll, textures and NBT. Hives as homes are not simulated yet. FlyingMoveControl clamps the pitch like Entity.setXRot, so a rotlerp that wraps to 359 gives 90 as in vanilla. Mob AI parity: 9 bee scenarios, 3609/3609 ticks; full harness 120/120. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 32 +- crates/horizon-client/src/entity_nbt.rs | 4 + crates/horizon-client/src/mobs.rs | 3 + crates/horizon-client/src/mobs/ai.rs | 31 +- crates/horizon-client/src/mobs/bee.rs | 1112 +++++++++++++++++ crates/horizon-client/src/mobs/body_anim.rs | 11 +- crates/horizon-client/src/mobs/control.rs | 4 +- crates/horizon-client/src/mobs/goals.rs | 142 ++- crates/horizon-client/src/mobs/living.rs | 14 +- crates/horizon-client/src/mobs/nav.rs | 3 + crates/horizon-client/src/mobs/render.rs | 18 + .../horizonlab/parity/VanillaMobAiOracle.java | 26 + tools/test_mob_ai_parity.py | 13 + 13 files changed, 1379 insertions(+), 34 deletions(-) create mode 100644 crates/horizon-client/src/mobs/bee.rs diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index b33ebde49..b5bfc213b 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -470,7 +470,7 @@ fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool { /// `player_down`: the scenario's player is no valid target (creative, or /// killed this tick). -fn print(out: &mut String, t: i32, i: usize, m: &Mob, player_down: bool) { +fn print(out: &mut String, t: i32, i: usize, m: &Mob, player_down: bool, now: i64) { let _ = write!(out, "{t} {i}"); if m.removed { // Entity.RemovalReason: the end of the death animation, else a discard. @@ -589,6 +589,21 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob, player_down: bool) { .map_or("-".into(), |p| format!("{},{},{}", p[0], p[1], p[2])); let _ = write!(out, "\tcg {} {held} {opened}", m.extra.variant3); } + if let Some(b) = horizon_client::mobs::bee::get(m) { + let anger = if b.anger_end > 0 { + b.anger_end - now + } else { + -1 + }; + let flower = b + .flower + .map_or("-".into(), |p| format!("{},{},{}", p[0], p[1], p[2])); + let _ = write!( + out, + "\tbee {} {anger} {} {} {flower}", + b.flags, b.ticks_without_nectar, b.flower_cooldown + ); + } out.push('\n'); } @@ -835,6 +850,10 @@ fn main() -> horizon_client::Result<()> { } } m.random = LegacyRandom::new(spec.seed); + if m.species() == Species::Bee { + // The oracle draws the constructor's cooldowns again once seeded. + horizon_client::mobs::bee::draw_cooldowns(&mut m); + } if horizon_client::mobs::monster_brain::has_brain(m.species()) { // The oracle delays the sensors again with the seeded random // and seeds RunOne's shuffles with the mob's seed. @@ -902,7 +921,7 @@ fn main() -> horizon_client::Result<()> { // from it, and the scenarios feed neither. let mut level_random = LegacyRandom::new(0); for (i, m) in mobs.iter().enumerate() { - print(&mut out, 0, i, m, s.creative); + print(&mut out, 0, i, m, s.creative, world.game_time); } // The MobWorld every step sees, over a snapshot of the mobs. macro_rules! mob_world { @@ -1152,7 +1171,14 @@ fn main() -> horizon_client::Result<()> { .iter() .any(|e| player_hurt(player.as_ref(), e) && player_damage(e) >= 20.0); for (i, m) in mobs.iter().enumerate() { - print(&mut out, t, i, m, s.creative || player_killed); + print( + &mut out, + t, + i, + m, + s.creative || player_killed, + world.game_time, + ); } for e in &events { if let MobEvent::Sound(name, _, volume, pitch) = e { diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 0efd328f4..4b1fb54b4 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -389,6 +389,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { crate::mobs::nautilus::to_nbt(m, map); } "minecraft:sulfur_cube" => crate::mobs::sulfur_cube::to_nbt(m, map), + "minecraft:bee" => crate::mobs::bee::to_nbt(m, map), "minecraft:sniffer" => crate::mobs::sniffer::to_nbt(m, map), "minecraft:wither" => { map.insert("Invul".into(), Tag::Int(m.extra.counter)); @@ -768,6 +769,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - if m.species() == crate::mobs::Species::SulfurCube { crate::mobs::sulfur_cube::from_nbt(&mut m, tag); } + if m.species() == crate::mobs::Species::Bee { + crate::mobs::bee::from_nbt(&mut m, tag); + } if m.species() == crate::mobs::Species::Creaking && let Some(Tag::IntArray(home)) = tag.get("home_pos") && home.len() == 3 diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 5f5ad325b..6c2bf25f4 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -12,6 +12,7 @@ pub mod animal_brain; pub mod aquatic; pub mod axolotl; pub mod bat; +pub mod bee; pub mod body_anim; pub mod brain; pub mod breeze; @@ -755,6 +756,8 @@ pub struct Extra { pub lone: bool, /// A breeze's or creaking's brain (`monster_brain`). pub brain: Option>, + /// A bee's nectar, anger, flower and hive state. + pub bee: Option>, } #[derive(Clone, Debug)] pub struct Mob { diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index e3aad61df..7c0ef8c61 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -105,6 +105,7 @@ pub enum Family { Nautilus, Strider, Bat, + Bee, } pub fn family(s: Species) -> Family { use Species as S; @@ -165,6 +166,7 @@ pub fn family(s: Species) -> Family { S::Shulker => Family::Shulker, S::Strider => Family::Strider, S::Bat => Family::Bat, + S::Bee => Family::Bee, _ => Family::Generic, } } @@ -221,6 +223,7 @@ pub fn register(m: &mut Mob) { Family::Nautilus => super::nautilus::register(m), Family::Strider => super::strider::register(m), Family::Bat => super::bat::register(m), + Family::Bee => super::bee::register(m), } } /// Mob.tick additions that run before the entity tick (creeper fuse, puffing). @@ -404,6 +407,9 @@ pub fn tick( if m.species() == Species::Bat { super::bat::tick(m); } + if m.species() == Species::Bee { + super::bee::tick(m, level_random); + } true } /// LivingEntity.updateSwingTime (6-tick swing duration). @@ -859,7 +865,8 @@ fn server_ai_step( // A creaking looked at stands still: its navigation, move, look and jump // controls wait (CreakingPathNavigation and the Creaking*Control). let frozen = super::creaking::is_creaking(m) && !super::creaking::can_move(m); - if !frozen { + // The bee's navigation waits while it pollinates. + if !frozen && !super::bee::pollinating(m) { m.nav_tick(w); } if super::monster_brain::has_brain(m.species()) { @@ -894,7 +901,10 @@ fn server_ai_step( } if !super::axolotl::is_playing_dead(m) { m.move_control_tick(w, events); - m.look_control_tick(); + // BeeLookControl: still while angry. + if !(m.species() == Species::Bee && super::bee::angry(m, w)) { + m.look_control_tick(); + } } m.jump_control_tick(); } @@ -919,6 +929,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { // SpellcasterIllager.customServerAiStep. Species::Evoker if m.extra.counter > 0 => m.extra.counter -= 1, Species::Bat => super::bat::server_ai_step(m, cx.w, cx.events), + Species::Bee => super::bee::server_ai_step(m, cx), _ => {} } } @@ -944,6 +955,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { Species::Ravager => super::ravager::ai_step(m, w, events), Species::Wither => super::wither::ai_step(m, w, events), Species::Allay => super::allay::ai_step(m), + Species::Bee => super::bee::ai_step(m, w), Species::Breeze => super::breeze::ai_step(m), Species::Sniffer => super::sniffer::ai_step(m, events), Species::HappyGhast => super::happy_ghast::ai_step(m, w), @@ -1183,6 +1195,14 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 { if m.species() == Species::Strider { return super::strider::walk_target_value(m, w, p); } + // Bee.getWalkTargetValue: any air block. + if m.species() == Species::Bee { + return if w.facts.is_air(w.world.block(p[0], p[1], p[2])) { + 10.0 + } else { + 0.0 + }; + } // AbstractNautilus and Creaking.getWalkTargetValue: everywhere alike. if matches!( m.species(), @@ -1221,6 +1241,10 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool { super::bat::hurt(m); true } + Species::Bee => { + super::bee::hurt(m); + true + } Species::Enderman => super::enderman::on_damage(m, source), Species::WitherSkeleton | Species::Blaze | Species::MagmaCube | Species::Strider if source.is_fire() => @@ -1258,6 +1282,9 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { if m.species() == Species::IronGolem { return super::golem::iron_hurt_target(m, who, cx); } + if m.species() == Species::Bee { + return super::bee::sting(m, who, cx); + } if matches!(m.species(), Species::Hoglin | Species::Zoglin) { return super::piglin::hoglin_hurt_target(m, who, cx); } diff --git a/crates/horizon-client/src/mobs/bee.rs b/crates/horizon-client/src/mobs/bee.rs new file mode 100644 index 000000000..30bf515c4 --- /dev/null +++ b/crates/horizon-client/src/mobs/bee.rs @@ -0,0 +1,1112 @@ +//! Bees (`Bee`): flying about (`FlyingMoveControl`, `BeeWanderGoal`), finding +//! flowers and hovering over them until they carry nectar +//! (`BeePollinateGoal`), `NeutralMob` anger at whoever hurts them, stinging +//! once and dying of it, and the hive and flower bookkeeping. Beehive block +//! entities are not simulated yet: no hive is ever valid, so bees never find, +//! enter or leave one, nor grow crops on the way home. +use super::{ + Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, + control::{LookKind, MoveKind}, + goals::{ + Breed, Cx, Float, FollowParent, Goal, HurtByTarget, MOVE, MeleeAttack, NearestTarget, + Tempt, goal_clone, reduced, + }, + nav::NavKind, + path::PathType, +}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use std::collections::HashMap; + +const FLAG_ROLL: u8 = 2; +const FLAG_HAS_STUNG: u8 = 4; +const FLAG_HAS_NECTAR: u8 = 8; + +/// The bee's own fields (`Bee`'s instance state and its synced flags). +#[derive(Clone, Debug)] +pub struct Bee { + /// `DATA_FLAGS_ID`: rolling, has stung, has nectar. + pub flags: u8, + /// `DATA_ANGER_END_TIME`, -1 when calm. + pub anger_end: i64, + /// `persistentAngerTarget`. + pub angry_at: Option, + pub roll: f32, + pub roll_o: f32, + pub time_since_sting: i32, + pub ticks_without_nectar: i32, + pub stay_out_of_hive: i32, + pub crops_grown: i32, + /// `remainingCooldownBeforeLocatingNewHive` and `...NewFlower`. + pub hive_cooldown: i32, + pub flower_cooldown: i32, + pub flower: Option<[i32; 3]>, + pub hive: Option<[i32; 3]>, + pub under_water: i32, + /// `BeePollinateGoal.pollinating`, read by the navigation and look control. + pub pollinating: bool, + /// The cooldowns `ValidateHiveGoal` and `ValidateFlowerGoal` draw when built. + pub validate_hive_cooldown: i32, + pub validate_flower_cooldown: i32, +} +impl Default for Bee { + fn default() -> Self { + Self { + flags: 0, + anger_end: -1, + angry_at: None, + roll: 0.0, + roll_o: 0.0, + time_since_sting: 0, + ticks_without_nectar: 0, + stay_out_of_hive: 0, + crops_grown: 0, + hive_cooldown: 0, + flower_cooldown: 0, + flower: None, + hive: None, + under_water: 0, + pollinating: false, + validate_hive_cooldown: 0, + validate_flower_cooldown: 0, + } + } +} + +fn st(m: &mut Mob) -> &mut Bee { + m.extra.bee.get_or_insert_with(Default::default) +} +pub fn get(m: &Mob) -> Option<&Bee> { + m.extra.bee.as_deref() +} +fn flag(m: &Mob, f: u8) -> bool { + get(m).is_some_and(|b| b.flags & f != 0) +} +fn set_flag(m: &mut Mob, f: u8, value: bool) { + let b = st(m); + if value { + b.flags |= f; + } else { + b.flags &= !f; + } +} +pub fn has_nectar(m: &Mob) -> bool { + flag(m, FLAG_HAS_NECTAR) +} +pub fn has_stung(m: &Mob) -> bool { + flag(m, FLAG_HAS_STUNG) +} +pub fn rolling(m: &Mob) -> bool { + flag(m, FLAG_ROLL) +} +/// `Bee.setHasNectar`: nectar resets the time without it. +pub fn set_has_nectar(m: &mut Mob, value: bool) { + if value { + st(m).ticks_without_nectar = 0; + } + set_flag(m, FLAG_HAS_NECTAR, value); +} +pub fn set_has_stung(m: &mut Mob, value: bool) { + set_flag(m, FLAG_HAS_STUNG, value); +} +pub fn pollinating(m: &Mob) -> bool { + m.species() == Species::Bee && get(m).is_some_and(|b| b.pollinating) +} +/// `BeeLookControl.resetXRotOnTick`: the pitch stays put while pollinating. +fn set_pollinating(m: &mut Mob, value: bool) { + st(m).pollinating = value; + m.ai.look.kind = if value { + LookKind::Fixed + } else { + LookKind::Default + }; +} +/// `Mth.nextInt(random, min, max)`. +fn next_int(m: &mut Mob, min: i32, max: i32) -> i32 { + m.random.next_int_between_inclusive(min, max).unwrap_or(min) +} + +/// `Bee(EntityType, Level)` with `registerGoals` and `createNavigation`. +pub fn register(m: &mut Mob) { + m.ai.mov.kind = MoveKind::Flying { + max_turn: 20.0, + hovers: true, + }; + m.ai.nav.kind = NavKind::Flying; + m.ai.nav.can_open_doors = false; + m.ai.nav.required_path_length = 48.0; + m.set_malus(PathType::Fire, -1.0); + m.set_malus(PathType::Water, -1.0); + m.set_malus(PathType::WaterBorder, 16.0); + m.set_malus(PathType::Cocoa, -1.0); + m.set_malus(PathType::Fence, -1.0); + let tempt = m.kind.tempt.clone(); + let g = &mut m.ai.goals; + g.add(0, BeeAttack(MeleeAttack::new(f64::from(1.4_f32), true))); + g.add(1, EnterHive); + g.add(2, Breed::new(1.0)); + g.add(3, Tempt::new(1.25, tempt, false)); + g.add(3, ValidateHive { last: -1 }); + g.add(3, ValidateFlower { last: -1 }); + g.add(4, Pollinate::default()); + g.add(5, FollowParent::new(1.25)); + g.add(5, LocateHive); + g.add(5, GoToHive::default()); + g.add(6, GoToKnownFlower::default()); + g.add(7, GrowCrop); + g.add(8, Wander); + g.add(9, Float); + // FloatGoal's constructor lets the navigation float. + m.ai.nav.can_float = true; + let t = &mut m.ai.targets; + t.add(1, HurtByTarget::new().alert().bee()); + t.add(2, BecomeAngryTarget::new()); + // ResetUniversalAngerTargetGoal only runs with the universalAnger rule. + m.extra.bee = Some(Box::default()); + draw_cooldowns(m); +} +/// The random draws of the constructor: the validate goals' cooldowns (built +/// in `registerGoals`), then the field initialiser of the flower cooldown. +/// The parity probe draws them again once the random is seeded. +pub fn draw_cooldowns(m: &mut Mob) { + let hive = next_int(m, 20, 40); + let flower = next_int(m, 20, 40); + let locate = next_int(m, 20, 60); + let b = st(m); + b.validate_hive_cooldown = hive; + b.validate_flower_cooldown = flower; + b.flower_cooldown = locate; +} + +// --- NeutralMob ------------------------------------------------------------- + +/// `NeutralMob.isAngry`. +pub fn angry(m: &Mob, w: &MobWorld) -> bool { + get(m).is_some_and(|b| b.anger_end > 0 && b.anger_end - w.game_time > 0) +} +/// `NeutralMob.stopBeingAngry`. +pub fn stop_being_angry(m: &mut Mob) { + m.ai.last_hurt_by = None; + m.ai.last_hurt_by_time = m.age as i32; + m.ai.target = None; + let b = st(m); + b.angry_at = None; + b.anger_end = -1; +} +/// `Bee.startPersistentAngerTimer`: 20 to 39 seconds. +fn start_anger_timer(m: &mut Mob, w: &MobWorld) { + let ticks = next_int(m, 400, 780); + st(m).anger_end = w.game_time + i64::from(ticks); +} +fn valid_player_target(w: &MobWorld) -> bool { + w.player + .as_ref() + .is_some_and(|p| !p.creative && !p.spectator) +} +/// `NeutralMob.updatePersistentAnger(level, false)`. +fn update_persistent_anger(m: &mut Mob, w: &MobWorld) { + let previous = m.ai.target; + let angry_at = get(m).and_then(|b| b.angry_at); + let dead_mob = |who: Who| match who { + Who::Mob(id) => w.seen(id).is_none_or(|s| !s.alive), + Who::Player => false, + }; + if let Some(p) = previous + && dead_mob(p) + && angry_at == Some(p) + { + stop_being_angry(m); + return; + } + if let Some(target) = m.ai.target + && angry_at != Some(target) + { + st(m).angry_at = Some(target); + start_anger_timer(m, w); + } + if angry_at.is_some() && !angry(m, w) { + stop_being_angry(m); + } + if angry_at == Some(Who::Player) && !valid_player_target(w) { + stop_being_angry(m); + } +} +/// `beeCanTarget`: angry and still armed. +fn can_target(m: &Mob, w: &MobWorld) -> bool { + angry(m, w) && !has_stung(m) +} + +// --- the bee's ticks ---------------------------------------------------------- + +/// `Bee.tick` after `super.tick()`: nectar drips (positions drawn from the +/// level's random even on the server), then the roll. +pub fn tick(m: &mut Mob, level_random: &mut LegacyRandom) { + if has_nectar(m) && get(m).is_some_and(|b| b.crops_grown < 10) && m.random.next_float() < 0.05 { + let mut i = 0; + while i < m.random.next_int_bound(2).unwrap_or(0) + 1 { + let _ = (level_random.next_double(), level_random.next_double()); + i += 1; + } + } + let roll = rolling(m); + let b = st(m); + b.roll_o = b.roll; + b.roll = if roll { + (b.roll + 0.2).min(1.0) + } else { + (b.roll - 0.24).max(0.0) + }; +} +/// `Bee.aiStep` after `super.aiStep()`. +pub fn ai_step(m: &mut Mob, w: &MobWorld) { + let b = st(m); + for c in [ + &mut b.stay_out_of_hive, + &mut b.hive_cooldown, + &mut b.flower_cooldown, + ] { + if *c > 0 { + *c -= 1; + } + } + let close = m + .target_info(w) + .is_some_and(|t| m.distance_sqr(t.position) < 4.0); + let roll = angry(m, w) && !has_stung(m) && close; + set_flag(m, FLAG_ROLL, roll); + if m.age.is_multiple_of(20) && !hive_valid(m, w) { + st(m).hive = None; + } +} +/// `Bee.customServerAiStep`: drowning, the sting's slow death, the time +/// without nectar and the anger. +pub fn server_ai_step(m: &mut Mob, cx: &mut Cx) { + let stung = has_stung(m); + let in_water = m.fluids.in_water; + let b = st(m); + b.under_water = if in_water { b.under_water + 1 } else { 0 }; + if b.under_water > 20 { + m.damage(1.0, Damage::of(DamageKind::Drown)); + } + if stung { + let b = st(m); + b.time_since_sting += 1; + let t = b.time_since_sting; + if t % 5 == 0 + && m.random + .next_int_bound((1200 - t).clamp(1, 1200)) + .unwrap_or(1) + == 0 + { + let health = m.health; + m.damage(health, Damage::of(DamageKind::Generic)); + } + } + if !has_nectar(m) { + st(m).ticks_without_nectar += 1; + } + update_persistent_anger(m, cx.w); +} +/// `Bee.hurtServer`: a hit ends pollinating. +pub fn hurt(m: &mut Mob) { + set_pollinating(m, false); +} +/// `Bee.doHurtTarget`: a sting for the attack damage, poison on normal (10 s) +/// and hard (18 s), then the bee has stung and calms down. +pub fn sting(m: &mut Mob, who: Who, cx: &mut Cx) { + let from = [m.position.x, m.position.y, m.position.z]; + let amount = (m.attrs.attack_damage as i32) as f32; + match who { + Who::Player => { + cx.events.push(MobEvent::AttackPlayer(amount, from)); + let seconds = if cx.w.difficulty.hard { 18 } else { 10 }; + cx.events.push(MobEvent::EffectPlayer { + effect: "minecraft:poison", + ticks: seconds * 20, + amplifier: 0, + }); + } + Who::Mob(id) => cx.events.push(MobEvent::AttackMob { + target: id, + amount, + source: Damage { + kind: DamageKind::Sting, + attacker: Some(Who::Mob(m.id)), + from: Some(from), + }, + }), + } + set_has_stung(m, true); + stop_being_angry(m); + if !m.silent { + cx.events + .push(MobEvent::Sound("entity.bee.sting", from, 1.0, 1.0)); + } +} + +// --- places ------------------------------------------------------------------- + +fn block_pos(m: &Mob) -> [i32; 3] { + [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ] +} +/// `Bee.closerThan`: `Vec3i.closerThan` from the bee's block. +fn closer_than(m: &Mob, p: [i32; 3], dist: i32) -> bool { + let b = block_pos(m); + let d = |i: usize| f64::from(p[i] - b[i]); + d(0) * d(0) + d(1) * d(1) + d(2) * d(2) < f64::from(dist * dist) +} +fn too_far(m: &Mob, p: [i32; 3]) -> bool { + !closer_than(m, p, 48) +} +/// `Bee.getBeehiveBlockEntity() != null`: hives are not simulated yet. +fn hive_valid(_m: &Mob, _w: &MobWorld) -> bool { + false +} +/// `EnvironmentAttributes.BEES_STAY_IN_HIVE`: the overworld's night, or rain. +fn bees_stay_in_hive(w: &MobWorld) -> bool { + let night = !w.nether && !w.end && (12542..23460).contains(&w.day_time.rem_euclid(24000)); + night || w.raining +} +fn tired_of_looking_for_nectar(m: &Mob) -> bool { + get(m).is_some_and(|b| b.ticks_without_nectar > 3600) +} +/// `Bee.wantsToEnterHive`. +fn wants_to_enter_hive(m: &Mob, w: &MobWorld) -> bool { + let Some(b) = get(m) else { return false }; + if b.stay_out_of_hive > 0 || b.pollinating || has_stung(m) || m.ai.target.is_some() { + return false; + } + // ... && !isHiveNearFire(): no hive, no fire. + has_nectar(m) || tired_of_looking_for_nectar(m) || bees_stay_in_hive(w) +} +fn drop_hive(m: &mut Mob) { + let b = st(m); + b.hive = None; + b.hive_cooldown = 200; +} +fn drop_flower(m: &mut Mob) { + st(m).flower = None; + let cooldown = next_int(m, 20, 60); + st(m).flower_cooldown = cooldown; +} +/// `Bee.attractsBees`. +pub fn attracts_bees(w: &MobWorld, p: [i32; 3]) -> bool { + let name = w.block_name(p[0], p[1], p[2]); + if !w.has_tag("minecraft:bee_attractive", name) { + return false; + } + if w.prop(p[0], p[1], p[2], "waterlogged") == Some("true") { + return false; + } + name != "minecraft:sunflower" || w.prop(p[0], p[1], p[2], "half") == Some("upper") +} +/// `BlockPos.withinBoxByManhattanDistance`: nearest first by Manhattan +/// distance, then x, y, and +z before -z. +fn manhattan_box(o: [i32; 3], rx: i32, ry: i32, rz: i32) -> Vec<[i32; 3]> { + let mut out = Vec::new(); + for depth in 0..=rx + ry + rz { + let max_x = rx.min(depth); + for x in -max_x..=max_x { + let max_y = ry.min(depth - x.abs()); + for y in -max_y..=max_y { + let z = depth - x.abs() - y.abs(); + if z <= rz { + out.push([o[0] + x, o[1] + y, o[2] + z]); + if z != 0 { + out.push([o[0] + x, o[1] + y, o[2] - z]); + } + } + } + } + } + out +} +/// `Bee.pathfindRandomlyTowards`. +fn pathfind_randomly_towards(m: &mut Mob, w: &MobWorld, p: [i32; 3]) { + let target = [ + f64::from(p[0]) + 0.5, + f64::from(p[1]), + f64::from(p[2]) + 0.5, + ]; + let here = block_pos(m); + let y_delta = target[1] as i32 - here[1]; + let y_adjust = if y_delta > 2 { + 4 + } else if y_delta < -2 { + -4 + } else { + 0 + }; + let dist = (p[0] - here[0]).abs() + (p[1] - here[1]).abs() + (p[2] - here[2]).abs(); + let (h, v) = if dist < 15 { + (dist / 2, dist / 2) + } else { + (6, 8) + }; + let max_rad = f64::from((std::f64::consts::PI / 10.0) as f32); + if let Some(at) = m.air_random_pos_towards(w, h, v, y_adjust, target, max_rad) { + m.ai.nav.max_visited_multiplier = 0.5; + m.nav_move_to(w, at, 1.0); + } +} + +// --- goals ---------------------------------------------------------------------- + +/// `BaseBeeGoal`: none of these run while the bee is angry. +fn calm(m: &Mob, w: &MobWorld) -> bool { + !angry(m, w) +} + +/// `BeeAttackGoal`: a melee attack while angry and armed. +#[derive(Clone, Debug)] +struct BeeAttack(MeleeAttack); +impl Goal for BeeAttack { + goal_clone!(); + fn name(&self) -> &'static str { + "BeeAttackGoal" + } + 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) && can_target(m, cx.w) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_continue(m, cx) && can_target(m, cx.w) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx); + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx); + } + fn every_tick(&self) -> bool { + self.0.every_tick() + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.tick(m, cx); + } +} + +/// `BeeBecomeAngryTargetGoal`: the player it is angry at, while armed. +#[derive(Clone, Debug)] +struct BecomeAngryTarget(NearestTarget); +impl BecomeAngryTarget { + fn new() -> Self { + Self( + NearestTarget::player(true) + .interval(10) + .gate(can_target) + // NeutralMob.isAngryAt: the persistent anger target. + .when(|m, _| get(m).is_some_and(|b| b.angry_at == Some(Who::Player))), + ) + } +} +impl Goal for BecomeAngryTarget { + goal_clone!(); + fn name(&self) -> &'static str { + "BeeBecomeAngryTargetGoal" + } + 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 { + can_target(m, cx.w) && m.ai.target.is_some() && self.0.can_continue(m, cx) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx); + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx); + } +} + +/// `BeeEnterHiveGoal`: into the hive beside it (none is ever valid yet). +#[derive(Clone, Debug)] +struct EnterHive; +impl Goal for EnterHive { + goal_clone!(); + fn name(&self) -> &'static str { + "BeeEnterHiveGoal" + } + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let close = get(m).and_then(|b| b.hive).is_some_and(|h| { + let d = |i: usize, v: f64| f64::from(h[i]) + 0.5 - v; + let (x, y, z) = (d(0, m.position.x), d(1, m.position.y), d(2, m.position.z)); + x * x + y * y + z * z < 4.0 + }); + let enter = close && wants_to_enter_hive(m, cx.w) && hive_valid(m, cx.w); + enter && calm(m, cx.w) + } + fn can_continue(&mut self, _m: &mut Mob, _cx: &mut Cx) -> bool { + false + } +} + +/// `ValidateHiveGoal`: now and then, forget a hive that is gone. +#[derive(Clone, Debug)] +struct ValidateHive { + last: i64, +} +impl Goal for ValidateHive { + goal_clone!(); + fn name(&self) -> &'static str { + "ValidateHiveGoal" + } + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let cooldown = get(m).map_or(0, |b| b.validate_hive_cooldown); + cx.w.game_time > self.last + i64::from(cooldown) && calm(m, cx.w) + } + fn can_continue(&mut self, _m: &mut Mob, _cx: &mut Cx) -> bool { + false + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(h) = get(m).and_then(|b| b.hive) + && cx.w.world.loaded(h[0], h[2]) + && !hive_valid(m, cx.w) + { + drop_hive(m); + } + self.last = cx.w.game_time; + } +} + +/// `ValidateFlowerGoal`: now and then, forget a flower that is gone. +#[derive(Clone, Debug)] +struct ValidateFlower { + last: i64, +} +impl Goal for ValidateFlower { + goal_clone!(); + fn name(&self) -> &'static str { + "ValidateFlowerGoal" + } + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let cooldown = get(m).map_or(0, |b| b.validate_flower_cooldown); + cx.w.game_time > self.last + i64::from(cooldown) && calm(m, cx.w) + } + fn can_continue(&mut self, _m: &mut Mob, _cx: &mut Cx) -> bool { + false + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(f) = get(m).and_then(|b| b.flower) + && cx.w.world.loaded(f[0], f[2]) + && !attracts_bees(cx.w, f) + { + drop_flower(m); + } + self.last = cx.w.game_time; + } +} + +/// `BeePollinateGoal`: fly to a flower within five blocks and hover about +/// over it; after 400 ticks there the bee carries nectar. +#[derive(Clone, Debug, Default)] +struct Pollinate { + successful: i32, + last_sound: i32, + hover: Option<[f64; 3]>, + ticks: i32, + /// `unreachableFlowerCache`: flowers and the game time until which they + /// count as out of reach. + unreachable: HashMap<[i32; 3], i64>, +} +impl Pollinate { + fn long_enough(&self) -> bool { + self.successful > 400 + } + /// `findNearbyFlower`: the first reachable flower, nearest first. + fn find_flower(&mut self, m: &mut Mob, w: &MobWorld) -> Option<[i32; 3]> { + let mut cache = HashMap::new(); + let mut found = None; + for p in manhattan_box(block_pos(m), 5, 5, 5) { + if !attracts_bees(w, p) { + continue; + } + let until = self.unreachable.get(&p).copied().unwrap_or(i64::MIN); + if w.game_time < until { + cache.insert(p, until); + continue; + } + if m.create_path_to(w, p, 1).is_some_and(|path| path.reached) { + found = Some(p); + break; + } + cache.insert(p, w.game_time + 600); + } + self.unreachable = cache; + found + } + fn set_wanted(&self, m: &mut Mob) { + if let Some(h) = self.hover { + m.ai.mov.set_wanted(h[0], h[1], h[2], f64::from(0.35_f32)); + } + } + fn offset(m: &mut Mob) -> f64 { + f64::from((m.random.next_float() * 2.0 - 1.0) * 0.333_333_34) + } +} +impl Goal for Pollinate { + goal_clone!(); + fn name(&self) -> &'static str { + "BeePollinateGoal" + } + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let usable = + if get(m).is_some_and(|b| b.flower_cooldown > 0) || has_nectar(m) || cx.w.raining { + false + } else if let Some(p) = self.find_flower(m, cx.w) { + st(m).flower = Some(p); + let at = [ + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ]; + m.nav_move_to(cx.w, at, f64::from(1.2_f32)); + true + } else { + let cooldown = next_int(m, 20, 60); + st(m).flower_cooldown = cooldown; + false + }; + usable && calm(m, cx.w) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let go = if !pollinating(m) || get(m).is_none_or(|b| b.flower.is_none()) || cx.w.raining { + false + } else if self.long_enough() { + m.random.next_float() < 0.2 + } else { + true + }; + go && calm(m, cx.w) + } + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + self.successful = 0; + self.ticks = 0; + self.last_sound = 0; + set_pollinating(m, true); + st(m).ticks_without_nectar = 0; + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + if self.long_enough() { + set_has_nectar(m, true); + } + set_pollinating(m, false); + m.nav_stop(); + st(m).flower_cooldown = 200; + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, _cx: &mut Cx) { + let Some(f) = get(m).and_then(|b| b.flower) else { + return; + }; + self.ticks += 1; + if self.ticks > 600 { + drop_flower(m); + set_pollinating(m, false); + st(m).flower_cooldown = 200; + return; + } + let flower = [ + f64::from(f[0]) + 0.5, + f64::from(f[1]) + f64::from(0.6_f32), + f64::from(f[2]) + 0.5, + ]; + if m.distance_to(flower) > 1.0 { + self.hover = Some(flower); + self.set_wanted(m); + return; + } + let hover = *self.hover.get_or_insert(flower); + let arrived = m.distance_to(hover) <= 0.1; + if !arrived && self.ticks > 600 { + drop_flower(m); + return; + } + let mut set_wanted = true; + if arrived { + if m.random.next_int_bound(25).unwrap_or(1) == 0 { + let x = flower[0] + Self::offset(m); + let z = flower[2] + Self::offset(m); + self.hover = Some([x, flower[1], z]); + m.nav_stop(); + } else { + set_wanted = false; + } + m.look_at(flower); + } + if set_wanted { + self.set_wanted(m); + } + self.successful += 1; + if m.random.next_float() < 0.05 && self.successful > self.last_sound + 60 { + self.last_sound = self.successful; + if !m.silent { + let at = [m.position.x, m.position.y, m.position.z]; + m.outbox + .push(MobEvent::Sound("entity.bee.pollinate", at, 1.0, 1.0)); + } + } + } +} + +/// `BeeLocateHiveGoal`: the nearest bee home with room (none yet). +#[derive(Clone, Debug)] +struct LocateHive; +impl Goal for LocateHive { + goal_clone!(); + fn name(&self) -> &'static str { + "BeeLocateHiveGoal" + } + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let b = get(m); + let usable = b.is_some_and(|b| b.hive_cooldown == 0 && b.hive.is_none()) + && wants_to_enter_hive(m, cx.w); + usable && calm(m, cx.w) + } + fn can_continue(&mut self, _m: &mut Mob, _cx: &mut Cx) -> bool { + false + } + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + // findNearbyHivesWithSpace finds no beehive block entity. + st(m).hive_cooldown = 200; + } +} + +/// `BeeGoToHiveGoal`: home when it wants to go in. +#[derive(Clone, Debug, Default)] +struct GoToHive { + travelling: i32, + blacklist: Vec<[i32; 3]>, + last_path: Option, + stuck: i32, +} +impl GoToHive { + fn reached(m: &Mob, p: [i32; 3]) -> bool { + closer_than(m, p, 2) + || m.ai + .nav + .path + .as_ref() + .is_some_and(|path| path.target == p && path.reached && path.is_done()) + } + fn drop_and_blacklist(&mut self, m: &mut Mob) { + if let Some(h) = get(m).and_then(|b| b.hive) { + self.blacklist.push(h); + while self.blacklist.len() > 3 { + self.blacklist.remove(0); + } + } + drop_hive(m); + } + fn pathfind_directly(m: &mut Mob, w: &MobWorld, p: [i32; 3]) -> bool { + let close_enough = if closer_than(m, p, 3) { 1 } else { 2 }; + m.ai.nav.max_visited_multiplier = 10.0; + let path = m.create_path_to(w, p, close_enough); + m.nav_move_to_path(path, 1.0); + m.ai.nav.path.as_ref().is_some_and(|path| path.reached) + } +} +impl Goal for GoToHive { + goal_clone!(); + fn name(&self) -> &'static str { + "BeeGoToHiveGoal" + } + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let usable = get(m).and_then(|b| b.hive).is_some_and(|h| { + !too_far(m, h) + && m.ai.home.is_none() + && wants_to_enter_hive(m, cx.w) + && !Self::reached(m, h) + && cx + .w + .has_tag("minecraft:beehives", cx.w.block_name(h[0], h[1], h[2])) + }); + usable && calm(m, cx.w) + } + fn start(&mut self, _m: &mut Mob, _cx: &mut Cx) { + self.travelling = 0; + self.stuck = 0; + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + self.travelling = 0; + self.stuck = 0; + m.nav_stop(); + m.ai.nav.max_visited_multiplier = 1.0; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(h) = get(m).and_then(|b| b.hive) else { + return; + }; + self.travelling += 1; + if self.travelling > reduced(2400) { + self.drop_and_blacklist(m); + } else if !m.ai.nav.is_in_progress() { + if !closer_than(m, h, 16) { + if too_far(m, h) { + drop_hive(m); + } else { + pathfind_randomly_towards(m, cx.w, h); + } + } else if !Self::pathfind_directly(m, cx.w, h) { + self.drop_and_blacklist(m); + } else if let Some(last) = &self.last_path + && m.ai + .nav + .path + .as_ref() + .is_some_and(|p| p.same_as(Some(last))) + { + self.stuck += 1; + if self.stuck > 60 { + drop_hive(m); + self.stuck = 0; + } + } else { + self.last_path = m.ai.nav.path.clone(); + } + } + } +} + +/// `BeeGoToKnownFlowerGoal`: back to the remembered flower after 600 ticks +/// without nectar. +#[derive(Clone, Debug, Default)] +struct GoToKnownFlower { + travelling: i32, +} +impl Goal for GoToKnownFlower { + goal_clone!(); + fn name(&self) -> &'static str { + "BeeGoToKnownFlowerGoal" + } + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let usable = get(m).is_some_and(|b| { + b.flower.is_some_and(|f| { + m.ai.home.is_none() && b.ticks_without_nectar > 600 && !closer_than(m, f, 2) + }) + }); + usable && calm(m, cx.w) + } + fn start(&mut self, _m: &mut Mob, _cx: &mut Cx) { + self.travelling = 0; + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + self.travelling = 0; + m.nav_stop(); + m.ai.nav.max_visited_multiplier = 1.0; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(f) = get(m).and_then(|b| b.flower) else { + return; + }; + self.travelling += 1; + if self.travelling > reduced(2400) { + drop_flower(m); + } else if !m.ai.nav.is_in_progress() { + if too_far(m, f) { + drop_flower(m); + } else { + pathfind_randomly_towards(m, cx.w, f); + } + } + } +} + +/// `BeeGrowCropGoal`: a bee with nectar and a hive grows crops below it. +#[derive(Clone, Debug)] +struct GrowCrop; +impl Goal for GrowCrop { + goal_clone!(); + fn name(&self) -> &'static str { + "BeeGrowCropGoal" + } + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + // The 0.3 roll comes only after the crop count: it draws randomness. + let usable = !get(m).is_some_and(|b| b.crops_grown >= 10) + && m.random.next_float() >= 0.3 + && has_nectar(m) + && hive_valid(m, cx.w); + usable && calm(m, cx.w) + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if m.random.next_int_bound(reduced(30)).unwrap_or(1) != 0 { + return; + } + let here = block_pos(m); + for i in 1..=2 { + let p = [here[0], here[1] - i, here[2]]; + if let Some(state) = grown(cx.w, p) { + cx.events.push(MobEvent::SetBlock { pos: p, state }); + st(m).crops_grown += 1; + } + } + } +} +/// The state a bee grows a `bee_growables` block to, if it can grow. +fn grown(w: &MobWorld, p: [i32; 3]) -> Option { + let name = w.block_name(p[0], p[1], p[2]); + if !w.has_tag("minecraft:bee_growables", name) { + return None; + } + let state = w.registry.state(w.world.block(p[0], p[1], p[2]))?; + let (key, max) = match name { + "minecraft:beetroots" => ("age", 3), + // TorchflowerCropBlock.getStateForAge(2): the flower itself. + "minecraft:torchflower_crop" => { + let age: i32 = state.properties.get("age")?.parse().ok()?; + return if age + 1 >= 2 { + w.registry.default_state("minecraft:torchflower") + } else { + let mut s = state.clone(); + s.properties.insert("age".into(), (age + 1).to_string()); + w.registry.id(&s) + }; + } + "minecraft:wheat" | "minecraft:carrots" | "minecraft:potatoes" => ("age", 7), + "minecraft:melon_stem" | "minecraft:pumpkin_stem" => ("age", 7), + "minecraft:sweet_berry_bush" => ("age", 3), + // CaveVinesBlock.performBonemeal: berries. + "minecraft:cave_vines" | "minecraft:cave_vines_plant" => { + if state.properties.get("berries").map(String::as_str) == Some("true") { + return None; + } + let mut s = state.clone(); + s.properties.insert("berries".into(), "true".into()); + return w.registry.id(&s); + } + _ => return None, + }; + let age: i32 = state.properties.get(key)?.parse().ok()?; + if age >= max { + return None; + } + let mut s = state.clone(); + s.properties.insert(key.into(), (age + 1).to_string()); + w.registry.id(&s) +} + +/// `BeeWanderGoal`: hover to a random spot ahead (or back towards a far hive). +#[derive(Clone, Debug)] +struct Wander; +impl Goal for Wander { + goal_clone!(); + fn name(&self) -> &'static str { + "BeeWanderGoal" + } + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + m.ai.nav.is_done() && m.random.next_int_bound(10).unwrap_or(1) == 0 + } + fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + m.ai.nav.is_in_progress() + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + // isHiveValid() is false: wander the way it looks. + let dir = m.view_vector(); + let max_rad = f64::from(std::f32::consts::FRAC_PI_2); + let at = m + .hover_random_pos(cx.w, 8, 7, dir[0], dir[2], max_rad, 3, 1) + .or_else(|| m.air_and_water_random_pos(cx.w, 8, 4, -2, dir[0], dir[2])); + if let Some(at) = at { + let p = [ + at[0].floor() as i32, + at[1].floor() as i32, + at[2].floor() as i32, + ]; + let path = m.create_path_to(cx.w, p, 1); + m.nav_move_to_path(path, 1.0); + } + } +} + +/// `FlyingPathNavigation.isStableDestination` for bees: anything above +/// something not air. +pub fn stable_destination(w: &MobWorld, p: [i32; 3]) -> bool { + !w.facts.is_air(w.world.block(p[0], p[1] - 1, p[2])) +} +/// `Bee.addAdditionalSaveData` (and NeutralMob's `anger_end_time`). +pub fn to_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) { + use horizon_world::nbt::Tag; + let b = get(m).cloned().unwrap_or_default(); + for (key, pos) in [("hive_pos", b.hive), ("flower_pos", b.flower)] { + match pos { + Some(p) => { + map.insert(key.into(), Tag::IntArray(p.to_vec())); + } + None => { + map.remove(&key.into()); + } + } + } + map.insert("HasNectar".into(), Tag::Byte(i8::from(has_nectar(m)))); + map.insert("HasStung".into(), Tag::Byte(i8::from(has_stung(m)))); + map.insert( + "TicksSincePollination".into(), + Tag::Int(b.ticks_without_nectar), + ); + map.insert("CannotEnterHiveTicks".into(), Tag::Int(b.stay_out_of_hive)); + map.insert("CropsGrownSincePollination".into(), Tag::Int(b.crops_grown)); + map.insert("anger_end_time".into(), Tag::Long(b.anger_end)); +} +/// `Bee.readAdditionalSaveData`. +pub fn from_nbt(m: &mut Mob, tag: &horizon_world::nbt::Tag) { + use horizon_world::nbt::Tag; + let int = |k: &str| match tag.get(k) { + Some(Tag::Int(v)) => Some(*v), + Some(Tag::Byte(v)) => Some(i32::from(*v)), + _ => None, + }; + let pos = |k: &str| match tag.get(k) { + Some(Tag::IntArray(p)) if p.len() == 3 => Some([p[0], p[1], p[2]]), + _ => None, + }; + set_has_nectar(m, int("HasNectar").unwrap_or(0) != 0); + set_has_stung(m, int("HasStung").unwrap_or(0) != 0); + let anger_end = match tag.get("anger_end_time") { + Some(Tag::Long(v)) => *v, + _ => -1, + }; + let b = st(m); + b.ticks_without_nectar = int("TicksSincePollination").unwrap_or(0); + b.stay_out_of_hive = int("CannotEnterHiveTicks").unwrap_or(0); + b.crops_grown = int("CropsGrownSincePollination").unwrap_or(0); + b.hive = pos("hive_pos"); + b.flower = pos("flower_pos"); + b.anger_end = anger_end; +} diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs index 20bcded10..4411d347b 100644 --- a/crates/horizon-client/src/mobs/body_anim.rs +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -993,10 +993,13 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { p, s, &Bee { - has_stinger: true, - on_ground: m.on_ground, - angry: m.extra.anger > 0, - roll_amount: 0.0, + has_stinger: !super::bee::has_stung(m), + on_ground: m.on_ground && m.velocity.length_squared() < 1.0e-7, + // The anger end time is cleared the tick after it passes. + angry: super::bee::get(m).is_some_and(|b| b.anger_end > 0), + // Bee.getRollAmount(partialTick). + roll_amount: super::bee::get(m) + .map_or(0.0, |b| b.roll_o + (b.roll - b.roll_o) * s.partial), }, ), Species::Bat => bat(p, s, m.extra.flag, &st[0], &st[1], a), diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index e562e9d1b..3df557362 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -167,7 +167,9 @@ impl Mob { let sd = (xd * xd + zd * zd).sqrt(); if yd.abs() > EPSILON || sd.abs() > EPSILON { let x_rot = -trig::atan2_degrees(yd, sd); - self.head_pitch = rotlerp(self.head_pitch, x_rot, max_turn); + // Entity.setXRot clamps: a pitch rotlerp wraps to 359 becomes 90. + self.head_pitch = + (rotlerp(self.head_pitch, x_rot, max_turn) % 360.0).clamp(-90.0, 90.0); self.ai.yya = if yd > 0.0 { speed } else { -speed }; } } else { diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 08544f89a..0d13b0e81 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -174,6 +174,26 @@ impl GoalSelector { // --- random positions (DefaultRandomPos / LandRandomPos / RandomPos) ------- +/// RandomPos.moveUpToAboveSolid: out of the solid blocks, then up to +/// `above` more blocks of air. +fn move_up_to_above_solid(w: &MobWorld, mut p: [i32; 3], above: i32) -> [i32; 3] { + if !w.solid(p[0], p[1], p[2]) { + return p; + } + p[1] += 1; + while p[1] <= 319 && w.solid(p[0], p[1], p[2]) { + p[1] += 1; + } + let first = p[1]; + while p[1] <= 319 && p[1] - first < above { + p[1] += 1; + if w.solid(p[0], p[1], p[2]) { + p[1] -= 1; + break; + } + } + p +} /// `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]); @@ -371,29 +391,89 @@ impl Mob { xd: f64, zd: f64, ) -> Option<[f64; 3]> { + // Every caller passes `(float) (Math.PI / 2)`. + let max_rad = f64::from(std::f32::consts::FRAC_PI_2); self.pick_best(w, |m| { - let d = m.random_direction_within( - 0.0, - f64::from(h), - v, - fly_height, - xd, - zd, - // Every caller passes `(float) (Math.PI / 2)`. - f64::from(std::f32::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) { + m.air_and_water_pos(w, h, v, fly_height, xd, zd, max_rad) + }) + } + /// AirAndWaterRandomPos.generateRandomPos. + #[allow(clippy::too_many_arguments)] + fn air_and_water_pos( + &mut self, + w: &MobWorld, + h: i32, + v: i32, + fly_height: i32, + xd: f64, + zd: f64, + max_rad: f64, + ) -> Option<[i32; 3]> { + let d = self.random_direction_within(0.0, f64::from(h), v, fly_height, xd, zd, max_rad)?; + let mut p = self.toward(f64::from(h), d); + if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || self.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; + } + } + (self.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p) + } + /// AirRandomPos.getPosTowards: an AirAndWaterRandomPos towards a point, + /// out of water. + pub fn air_random_pos_towards( + &mut self, + w: &MobWorld, + h: i32, + v: i32, + fly_height: i32, + to: [f64; 3], + max_rad: f64, + ) -> Option<[f64; 3]> { + let (xd, zd) = (to[0] - self.position.x, to[2] - self.position.z); + self.pick_best(w, |m| { + let p = m.air_and_water_pos(w, h, v, fly_height, xd, zd, max_rad)?; + (w.fluid(p[0], p[1], p[2]) != crate::blocks::Fluid::Water).then_some(p) + }) + } + /// HoverRandomPos.getPos: a stable spot within the radians of a + /// direction, raised a random `hover_min..=hover_max` blocks above the + /// solid ground it is in, out of water and free of path maluses. + #[allow(clippy::too_many_arguments)] + pub fn hover_random_pos( + &mut self, + w: &MobWorld, + h: i32, + v: i32, + xd: f64, + zd: f64, + max_rad: f64, + hover_max: i32, + hover_min: i32, + ) -> Option<[f64; 3]> { + self.pick_best(w, |m| { + let d = m.random_direction_within(0.0, f64::from(h), v, 0, xd, zd, max_rad)?; + // LandRandomPos.generateRandomPosTowardDirection + let p = m.toward(f64::from(h), d); + if p[1] < crate::chunk::MIN_Y + || p[1] >= 320 + || m.restricted(f64::from(h), p) + || !m.stable_destination(w, 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) + let above = m + .random + .next_int_bound(hover_max - hover_min + 1) + .unwrap_or(0) + + hover_min; + let p = move_up_to_above_solid(w, p, above); + let water = w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water; + (!water && m.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p) }) } /// LandRandomPos.getPos @@ -1340,6 +1420,9 @@ pub struct HurtByTarget { pub alert_except: Vec, /// Attackers ignored (e.g. zombified piglins ignore other zombified piglins). pub ignore: Vec, + /// `Bee.BeeHurtByOtherGoal`: kept only while angry, and alerting others + /// only when the attacker is in sight. + pub bee: bool, timestamp: i32, st: TargetState, } @@ -1349,6 +1432,7 @@ impl HurtByTarget { alert: false, alert_except: vec![], ignore: vec![], + bee: false, timestamp: 0, st: TargetState { unseen_memory: 300, @@ -1364,6 +1448,10 @@ impl HurtByTarget { self.ignore = s.to_vec(); self } + pub fn bee(mut self) -> Self { + self.bee = true; + self + } } impl Default for HurtByTarget { fn default() -> Self { @@ -1372,6 +1460,13 @@ impl Default for HurtByTarget { } impl Goal for HurtByTarget { goal_clone!(); + fn name(&self) -> &'static str { + if self.bee { + "BeeHurtByOtherGoal" + } else { + "HurtByTarget" + } + } fn flags(&self) -> u8 { TARGET } @@ -1396,6 +1491,9 @@ impl Goal for HurtByTarget { t.alive && t.can_be_seen_as_enemy && !(t.is_player && t.creative) } fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if self.bee && !super::bee::angry(m, cx.w) { + return false; + } target_continue(&mut self.st, true, m, cx) } fn start(&mut self, m: &mut Mob, cx: &mut Cx) { @@ -1426,6 +1524,10 @@ impl Goal for HurtByTarget { .filter(|s| Who::Mob(s.id) != by) .map(|s| s.id) .collect(); + // Bee.BeeHurtByOtherGoal.alertOther: only with the attacker in sight. + if self.bee && !ids.is_empty() && !m.sees(cx.w, by) { + return; + } for other in ids { cx.events.push(MobEvent::SetTarget { mob: other, diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 9927ea69c..772041edd 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -346,10 +346,10 @@ impl Mob { self.vertical_collision_below = vertical && wanted.y < 0.0; self.on_ground = self.vertical_collision_below; // Strider.checkFallDamage: lava breaks any fall, and the fluid state - // waits for the next baseTick; Bat.checkFallDamage does nothing. + // waits for the next baseTick; Bat and Bee.checkFallDamage do nothing. if self.kind.flags.lava_walker && self.fluids.in_lava { self.fall_distance = 0.0; - } else if self.kind.species != super::Species::Bat { + } else if !matches!(self.kind.species, super::Species::Bat | super::Species::Bee) { self.check_fall_damage(w, moved, events); } // restituteMovementAfterCollisions with no bounciness: the colliding @@ -782,9 +782,15 @@ impl Mob { self.ai.no_jump_delay = 0; } } - /// Mob.jumpInLiquid: floaters rise 0.04 per tick, others 0.3. + /// Mob.jumpInLiquid: floaters rise 0.04 per tick, others 0.3; bees 0.01. fn jump_in_liquid(&mut self) { - self.velocity.y += if self.ai.nav.can_float { 0.04 } else { 0.3 }; + self.velocity.y += if self.species() == super::Species::Bee { + 0.01 + } else if self.ai.nav.can_float { + 0.04 + } else { + 0.3 + }; } pub fn jump_from_ground(&mut self, w: &MobWorld) { if self.species() == super::Species::Rabbit { diff --git a/crates/horizon-client/src/mobs/nav.rs b/crates/horizon-client/src/mobs/nav.rs index a2cb57670..24dafa48d 100644 --- a/crates/horizon-client/src/mobs/nav.rs +++ b/crates/horizon-client/src/mobs/nav.rs @@ -562,6 +562,9 @@ impl Mob { } /// PathNavigation.isStableDestination for the mob's navigation. pub fn stable_destination(&self, w: &MobWorld, p: [i32; 3]) -> bool { + if self.species() == super::Species::Bee { + return super::bee::stable_destination(w, p); + } // StriderPathNavigation: lava too. if self.kind.flags.lava_walker && w.block_name(p[0], p[1], p[2]) == "minecraft:lava" { return true; diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 01d842541..a3b29f63b 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -263,6 +263,24 @@ pub fn body(m: &Mob) -> (String, String) { "entity/strider/strider" }), ), + // BeeRenderer.getTextureLocation: angry, carrying nectar, or both. + S::Bee => { + let angry = super::bee::get(m).is_some_and(|b| b.anger_end > 0); + let nectar = super::bee::has_nectar(m); + let texture = match (angry, nectar) { + (true, true) => "entity/bee/bee_angry_nectar", + (true, false) => "entity/bee/bee_angry", + (false, true) => "entity/bee/bee_nectar", + (false, false) => "entity/bee/bee", + }; + let layer = baby_or(m, "bee#main", "bee_baby#main"); + let texture = if layer.starts_with("bee_baby") { + b(texture) + } else { + texture.to_owned() + }; + (layer, texture) + } S::Squid => ( baby_or(m, "squid#main", "squid_baby#main"), b("entity/squid/squid"), 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 6b034411b..80559155a 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -615,6 +615,20 @@ public final class VanillaMobAiOracle { if (cooldown > 0) brain.setMemory(MemoryModuleType.TRANSPORT_ITEMS_COOLDOWN_TICKS, cooldown); else brain.eraseMemory(MemoryModuleType.TRANSPORT_ITEMS_COOLDOWN_TICKS); } + if (mob instanceof net.minecraft.world.entity.animal.bee.Bee bee) { + // The constructor's draws, made again with the seeded random: the validate + // goals' cooldowns (registerGoals), then the flower cooldown's initialiser. + var rnd = bee.getRandom(); + int hive = net.minecraft.util.Mth.nextInt(rnd, 20, 40); + int flower = net.minecraft.util.Mth.nextInt(rnd, 20, 40); + for (WrappedGoal g : ((GoalSelector) get(bee, "goalSelector")).getAvailableGoals()) { + String n = g.getGoal().getClass().getSimpleName(); + if (n.equals("ValidateHiveGoal")) field(g.getGoal().getClass(), "VALIDATE_HIVE_COOLDOWN").setInt(g.getGoal(), hive); + if (n.equals("ValidateFlowerGoal")) field(g.getGoal().getClass(), "validateFlowerCooldown").setInt(g.getGoal(), flower); + } + field(net.minecraft.world.entity.animal.bee.Bee.class, "remainingCooldownBeforeLocatingNewFlower") + .setInt(bee, net.minecraft.util.Mth.nextInt(rnd, 20, 60)); + } @SuppressWarnings("unchecked") Map> sensors = (Map>) get(brain, "sensors"); for (Sensor sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom()); @@ -986,6 +1000,18 @@ public final class VanillaMobAiOracle { sb.append("\tcg ").append(golem.getState().ordinal()).append(' ').append(stack(golem.getMainHandItem())).append(' ') .append(opened == null ? "-" : pos((BlockPos) opened)); } + if (m instanceof net.minecraft.world.entity.animal.bee.Bee bee) { + // Flags (roll 2, stung 4, nectar 8), anger left, ticks without nectar, flower cooldown, flower. + Object acc = field(net.minecraft.world.entity.animal.bee.Bee.class, "DATA_FLAGS_ID").get(null); + @SuppressWarnings("unchecked") + byte flags = bee.getEntityData().get((net.minecraft.network.syncher.EntityDataAccessor) acc); + long end = bee.getPersistentAngerEndTime(); + BlockPos flower = bee.getSavedFlowerPos(); + sb.append("\tbee ").append(flags).append(' ').append(end > 0 ? end - bee.level().getGameTime() : -1).append(' ') + .append(field(net.minecraft.world.entity.animal.bee.Bee.class, "ticksWithoutNectarSinceExitingHive").getInt(bee)).append(' ') + .append(field(net.minecraft.world.entity.animal.bee.Bee.class, "remainingCooldownBeforeLocatingNewFlower").getInt(bee)).append(' ') + .append(flower == null ? "-" : pos(flower)); + } out.println(sb); } diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 6cbdc4562..2b66d9b27 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -237,6 +237,19 @@ def scenarios(): CAVE = ['fill -5 -60 -5 5 -54 5 minecraft:stone', 'fill -4 -60 -4 4 -55 4 minecraft:air'] for i, seed in enumerate([144, 145, 146]): add(f'bat_cave_{i}', 400, CAVE + [f'mob minecraft:bat 0.5 -58 0.5 {90 * i} {seed} persistent']) + # Bees: wandering over grass (HoverRandomPos), pollinating a flower bed until they carry nectar, + # drawn to a player holding a flower, staying home at night and in the rain (no hive to find), + # drowning in a pool, and angered by a hit: they chase and sting the player once, then die of it. + FLOWERS = 'fill 3 -60 2 5 -60 4 minecraft:dandelion' + for i, seed in enumerate([151, 152]): + add(f'bee_alone_{i}', 400, [f'mob minecraft:bee 0.5 -58 0.5 {90 * i} {seed} persistent']) + for i, seed in enumerate([153, 154]): + add(f'bee_flowers_{i}', 700, [FLOWERS, f'mob minecraft:bee 0.5 -58 0.5 {180 * i} {seed} persistent']) + add('bee_tempted', 200, ['player 6.5 -60 0.5 hand=minecraft:dandelion', 'mob minecraft:bee 0.5 -58 0.5 0 155 persistent']) + add('bee_night', 300, [FLOWERS, 'mob minecraft:bee 0.5 -58 0.5 0 156 persistent'], 'time=18000') + add('bee_rain', 300, [FLOWERS, 'mob minecraft:bee 0.5 -58 0.5 0 157 persistent'], 'rain') + add('bee_pool', 200, ['fill -3 -63 -3 3 -61 3 minecraft:water', 'mob minecraft:bee 0.5 -62 0.5 0 158 persistent']) + add('bee_sting', 400, ['player 4.5 -60 0.5', 'mob minecraft:bee 0.5 -58 0.5 0 159 persistent', 'hurt 20 0']) return s