Bees live in hives and nests: they go home, come out in the morning and make honey (#208)

BeehiveBlockEntity (crate::beehive): up to three bees stored as entity
tags, out when their time is up (not at night, in the rain or through a
blocked front unless in an emergency), honey for nectar, the flower they
knew; vanilla's bees / flower_pos save format. Bees find a hive with room
(BeeLocateHiveGoal), fly home and go in (BeeEnterHiveGoal through
MobEvent::EnterHive). In the game hives tick, breaking one lets the bees
out angry unless smoked, fire empties it, dispensers release them.

mob_ai: bee_hive_night, _rain, _morning and _honey match vanilla.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-15 09:14:21 +02:00
parent b5a2afb71e
commit 111b237b6d
13 changed files with 1105 additions and 47 deletions
+187 -2
View File
@@ -5,6 +5,7 @@
//! usage: mob_ai_probe RESOURCES SCENARIOS OUTPUT
use horizon_client::{
assets::Assets,
beehive::HiveHost,
biome::Biomes,
blocks::BlockFacts,
chunk::{Chunk, HEIGHT, MIN_Y},
@@ -27,7 +28,13 @@ use horizon_core::{
random::LegacyRandom,
};
use horizon_world::{chunk::BlockState, registry::BlockRegistry, registry::BlockStateId};
use std::{collections::BTreeMap, fmt::Write as _, fs, path::Path, sync::Arc};
use std::{
collections::{BTreeMap, HashMap},
fmt::Write as _,
fs,
path::Path,
sync::Arc,
};
struct MobSpec {
kind: String,
@@ -54,6 +61,8 @@ struct Scenario {
hearts: Vec<Vec<String>>,
/// `ServerLevel.isSpawningMonsters`.
spawning: bool,
/// The day time moves on with every tick.
daycycle: bool,
/// The player hits a mob for 1 at the start of a tick: (tick, mob index).
hurts: Vec<(i32, usize)>,
/// The player feeds an animal at the start of a tick (Animal.mobInteract):
@@ -85,6 +94,7 @@ fn parse(text: &str) -> Vec<Scenario> {
"thunder" => s.thunder = true,
"levelseed" => {}
"spawning" => s.spawning = true,
"daycycle" => s.daycycle = true,
_ => panic!("unknown scenario option {kv}"),
}
}
@@ -407,6 +417,65 @@ impl HeartHost for Host<'_> {
self.spawning
}
}
/// A scenario's beehives as `BeehiveBlockEntity.serverTick` sees the level:
/// the bees let out are newcomers seeded as the oracle seeds them.
struct ProbeHive<'a, 'w> {
w: &'a MobWorld<'w>,
random: &'a mut LegacyRandom,
types: &'a HashMap<String, Arc<MobType>>,
/// The index of the first newcomer of this tick.
first: usize,
added: &'a mut Vec<Mob>,
honey: &'a mut Vec<([i32; 3], i32)>,
events: &'a mut Vec<MobEvent>,
}
impl HiveHost for ProbeHive<'_, '_> {
fn random(&mut self) -> &mut LegacyRandom {
self.random
}
fn bees_stay_in_hive(&self, _at: [i32; 3]) -> bool {
horizon_client::mobs::bee::bees_stay_in_hive(self.w)
}
fn blocked(&self, at: [i32; 3]) -> bool {
!self.w.block_collision_boxes(at[0], at[1], at[2]).is_empty()
}
fn set_honey_level(&mut self, at: [i32; 3], level: i32) {
self.honey.push((at, level));
}
fn load(&mut self, tag: &horizon_world::nbt::Tag) -> Option<Mob> {
let index = self.first + self.added.len();
let mut m =
horizon_client::entity_nbt::mob_from_nbt(tag, self.types, 100_000 + index as u32)?;
if m.species() != Species::Bee {
return None;
}
m.random = LegacyRandom::new(spawn_seed(index));
horizon_client::mobs::bee::draw_cooldowns(&mut m);
Some(m)
}
fn add(&mut self, m: Mob) -> bool {
self.added.push(m);
true
}
fn sound(&mut self, name: &'static str, at: [f64; 3]) {
self.events.push(MobEvent::Sound(name, at, 1.0, 1.0));
}
}
/// The hive's honey level and front from its block state.
fn hive_state(registry: &BlockRegistry, world: &World, at: [i32; 3]) -> (Option<i32>, [i32; 2]) {
let props = registry
.state(world.block(at[0], at[1], at[2]))
.map(|s| s.properties.clone())
.unwrap_or_default();
let honey = props.get("honey_level").and_then(|v| v.parse().ok());
let facing = horizon_client::beehive::facing_step(props.get("facing").map(String::as_str));
(honey, facing)
}
fn is_hive(b: &[String]) -> bool {
b[0] == "block"
&& (b[4].starts_with("minecraft:beehive") || b[4].starts_with("minecraft:bee_nest"))
}
/// The heart's state, block entity and the level random, as the oracle
/// prints them.
fn print_heart(
@@ -702,6 +771,12 @@ fn main() -> horizon_client::Result<()> {
let motion = horizon_client::motion::MotionResources::load(root, &assets)?;
let data = MobData::load(root, &facts);
let types = MobTypes::load(root)?;
// The types a bee leaving its hive is loaded with (EntityType.loadEntityRecursive).
let arc_types: HashMap<String, Arc<MobType>> = types
.types
.iter()
.map(|(k, v)| (k.clone(), Arc::new(v.clone())))
.collect();
let biomes = Biomes::load(root)?;
let items = Items::load(root, registry, &facts)?;
let tables = LightTables::load(root, registry, &facts)?;
@@ -744,6 +819,11 @@ fn main() -> horizon_client::Result<()> {
let n = |i: usize| b[i].parse::<i32>().unwrap();
if b[0] == "block" || b[0] == "chest" {
world.set(n(1), n(2), n(3), state(registry, &b[4]))?;
if is_hive(b) {
world
.block_entities
.insert((n(1), n(2), n(3)), BlockEntity::Beehive(Box::default()));
}
if b[0] == "chest" {
// chest X Y Z STATE SLOTS: item*count or - per slot.
let mut slots = vec![None; 27];
@@ -830,6 +910,7 @@ fn main() -> horizon_client::Result<()> {
&mut Vec::new(),
),
"inlove" => m.extra.in_love = 600,
"nectar" => horizon_client::mobs::bee::set_has_nectar(&mut m, true),
"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(),
@@ -936,7 +1017,7 @@ fn main() -> horizon_client::Result<()> {
data: &data,
player: player.clone(),
others: $snapshot,
daylight: (s.time.rem_euclid(24000)) < 12000,
daylight: (world.day_time.rem_euclid(24000)) < 12000,
game_time: world.game_time,
day_time: world.day_time,
raining: s.rain,
@@ -956,6 +1037,9 @@ fn main() -> horizon_client::Result<()> {
}
for t in 1..=s.ticks {
world.game_time += 1;
if s.daycycle {
world.day_time = s.time + i64::from(t);
}
let mut heart_events_later: Vec<HeartEvent> = Vec::new();
// Creaking.tick reads the heart's block entity.
for (at, h) in &hearts {
@@ -1121,6 +1205,41 @@ fn main() -> horizon_client::Result<()> {
_ => {}
}
}
// BeeEnterHiveGoal.start: BeehiveBlockEntity.addOccupant.
let entering: Vec<[i32; 3]> = events[from.min(events.len())..]
.iter()
.filter_map(|e| match e {
MobEvent::EnterHive { hive, .. } => Some(*hive),
_ => None,
})
.collect();
for at in entering {
let key = (at[0], at[1], at[2]);
let Some(BlockEntity::Beehive(mut hive)) = world.block_entities.remove(&key)
else {
continue;
};
let tag = horizon_client::entity_nbt::mob_to_nbt(&mobs[i], [0; 4], None);
let flower = horizon_client::mobs::bee::get(&mobs[i]).and_then(|b| b.flower);
let mut honey = Vec::new();
let stored = {
let w = mob_world!(&snapshot);
let mut host = ProbeHive {
w: &w,
random: &mut scratch,
types: &arc_types,
first: 0,
added: &mut Vec::new(),
honey: &mut honey,
events: &mut events,
};
hive.add_occupant(at, tag, flower, &mut host)
};
world.block_entities.insert(key, BlockEntity::Beehive(hive));
if stored {
mobs[i].removed = true;
}
}
// 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) {
@@ -1153,6 +1272,43 @@ fn main() -> horizon_client::Result<()> {
added.append(&mut host.added);
}
drop(w);
// Then the hives (BeehiveBlockEntity.serverTick).
let mut hive_keys: Vec<(i32, i32, i32)> = world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::Beehive(_)))
.map(|(k, _)| *k)
.collect();
hive_keys.sort_unstable();
let mut honey = Vec::new();
for key in hive_keys {
let at = [key.0, key.1, key.2];
let (level, facing) = hive_state(registry, &world, at);
let Some(BlockEntity::Beehive(mut hive)) = world.block_entities.remove(&key) else {
continue;
};
{
let w = mob_world!(&snapshot);
let mut host = ProbeHive {
w: &w,
random: &mut scratch,
types: &arc_types,
first: mobs.len() + born.len(),
added: &mut added,
honey: &mut honey,
events: &mut events,
};
hive.server_tick(at, facing, level, &mut host);
}
world.block_entities.insert(key, BlockEntity::Beehive(hive));
}
for (at, level) in honey {
if let Some(mut st) = registry.state(world.block(at[0], at[1], at[2])).cloned() {
st.properties
.insert("honey_level".to_owned(), level.to_string());
world.set(at[0], at[1], at[2], registry.resolve(&st)?)?;
}
}
mobs.append(&mut born);
mobs.append(&mut added);
for e in &heart_events {
@@ -1235,6 +1391,35 @@ fn main() -> horizon_client::Result<()> {
}
);
}
for b in s.blocks.iter().filter(|b| is_hive(b)) {
let n = |i: usize| b[i].parse::<i32>().unwrap();
let Some(BlockEntity::Beehive(hive)) =
world.block_entities.get(&(n(1), n(2), n(3)))
else {
continue;
};
let (level, _) = hive_state(registry, &world, [n(1), n(2), n(3)]);
let bees: Vec<String> = hive
.bees
.iter()
.map(|b| format!("{}/{}", b.ticks_in_hive, b.min_ticks_in_hive))
.collect();
let _ = writeln!(
out,
"{t} hive {},{},{} honey {} bees {} flower {}",
b[1],
b[2],
b[3],
level.unwrap_or(-1),
if bees.is_empty() {
"-".into()
} else {
bees.join(",")
},
hive.flower
.map_or("-".into(), |f| format!("{},{},{}", f[0], f[1], f[2]))
);
}
for line in traces {
let _ = writeln!(out, "{line}");
}
+438
View File
@@ -0,0 +1,438 @@
//! Beehives and bee nests (`BeehiveBlockEntity`): up to three bees stored as
//! entity tags, let out when their time inside is up (never at night or in
//! the rain, nor through a blocked front, unless the hive is emptied in an
//! emergency), honey for every bee coming home with nectar. The host (the game
//! or the mob AI probe) loads and adds the bees through [`HiveHost`].
use crate::mobs::{Mob, Species, bee};
use horizon_core::random::{LegacyRandom, RandomSource};
use horizon_world::nbt::{Compound, Tag};
pub const MAX_OCCUPANTS: usize = 3;
/// `BeehiveBlockEntity.IGNORED_BEE_TAGS`: dropped from a bee going in, and
/// again from the tag it comes out with.
const IGNORED_BEE_TAGS: [&str; 25] = [
"Air",
"drop_chances",
"equipment",
"Brain",
"CanPickUpLoot",
"DeathTime",
"fall_distance",
"FallFlying",
"Fire",
"HurtTime",
"LeftHanded",
"Motion",
"NoGravity",
"OnGround",
"PortalCooldown",
"Pos",
"Rotation",
"sleeping_pos",
"CannotEnterHiveTicks",
"TicksSincePollination",
"CropsGrownSincePollination",
"hive_pos",
"Passengers",
"leash",
"UUID",
];
/// `BeehiveBlockEntity`: the bees inside and the flower one of them knew.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Beehive {
pub bees: Vec<Occupant>,
pub flower: Option<[i32; 3]>,
}
/// `BeehiveBlockEntity.Occupant`: a bee's tag (with its `id`), its time in
/// the hive and the time it stays at least.
#[derive(Clone, Debug, PartialEq)]
pub struct Occupant {
pub entity_data: Tag,
pub ticks_in_hive: i32,
pub min_ticks_in_hive: i32,
}
/// `BeehiveBlockEntity.BeeReleaseStatus`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Release {
HoneyDelivered,
BeeReleased,
Emergency,
}
/// What a hive needs from the level it is in.
pub trait HiveHost {
/// `level.getRandom()`.
fn random(&mut self) -> &mut LegacyRandom;
/// `EnvironmentAttributes.BEES_STAY_IN_HIVE` at a position.
fn bees_stay_in_hive(&self, at: [i32; 3]) -> bool;
/// A non-empty collision shape at a block.
fn blocked(&self, at: [i32; 3]) -> bool;
/// `BlockState.setValue(HONEY_LEVEL, level)` on the hive.
fn set_honey_level(&mut self, at: [i32; 3], level: i32);
/// `EntityType.loadEntityRecursive` (the tag has its `id` and a `Pos`):
/// a new entity, or `None` for anything but a `#beehive_inhabitors`.
fn load(&mut self, tag: &Tag) -> Option<Mob>;
/// `Level.addFreshEntity`.
fn add(&mut self, m: Mob) -> bool;
fn sound(&mut self, name: &'static str, at: [f64; 3]);
}
fn strip_ignored(c: &mut Compound) {
for key in IGNORED_BEE_TAGS {
c.remove(&key.into());
}
}
fn int(tag: Option<&Tag>) -> Option<i32> {
match tag {
Some(Tag::Int(v)) => Some(*v),
_ => None,
}
}
fn pos(tag: Option<&Tag>) -> Option<[i32; 3]> {
match tag {
Some(Tag::IntArray(p)) if p.len() == 3 => Some([p[0], p[1], p[2]]),
_ => None,
}
}
impl Occupant {
/// `Occupant.of`: the bee's saved tag without the ignored tags, staying
/// 2400 ticks with nectar, else 600.
pub fn of(mut tag: Tag) -> Self {
if let Tag::Compound(c) = &mut tag {
strip_ignored(c);
}
let nectar = matches!(tag.get("HasNectar"), Some(Tag::Byte(v)) if *v != 0);
Self {
entity_data: tag,
ticks_in_hive: 0,
min_ticks_in_hive: if nectar { 2400 } else { 600 },
}
}
/// `Occupant.create`: a worldgen nest's bee, a bare bee tag.
pub fn create(ticks_in_hive: i32) -> Self {
Self {
entity_data: Tag::compound([("id", Tag::String("minecraft:bee".into()))]),
ticks_in_hive,
min_ticks_in_hive: 600,
}
}
fn has_nectar(&self) -> bool {
matches!(self.entity_data.get("HasNectar"), Some(Tag::Byte(v)) if *v != 0)
}
fn from_nbt(tag: &Tag) -> Option<Self> {
let data = tag.get("entity_data")?;
if !matches!(data, Tag::Compound(c) if c.contains_key(&"id".into())) {
return None;
}
Some(Self {
entity_data: data.clone(),
ticks_in_hive: int(tag.get("ticks_in_hive"))?,
min_ticks_in_hive: int(tag.get("min_ticks_in_hive"))?,
})
}
fn to_nbt(&self) -> Tag {
Tag::compound([
("entity_data", self.entity_data.clone()),
("ticks_in_hive", Tag::Int(self.ticks_in_hive)),
("min_ticks_in_hive", Tag::Int(self.min_ticks_in_hive)),
])
}
}
impl Beehive {
pub fn full(&self) -> bool {
self.bees.len() == MAX_OCCUPANTS
}
/// `loadAdditional`: `bees` (all or none, as the list codec reads them)
/// and `flower_pos`.
pub fn from_nbt(tag: &Tag) -> Self {
let bees = match tag.get("bees") {
Some(Tag::List(list)) => list
.iter()
.map(Occupant::from_nbt)
.collect::<Option<Vec<_>>>()
.unwrap_or_default(),
_ => Vec::new(),
};
Self {
bees,
flower: pos(tag.get("flower_pos")),
}
}
/// `saveAdditional`.
pub fn to_nbt(&self) -> Vec<(&'static str, Tag)> {
let mut out = vec![(
"bees",
Tag::List(self.bees.iter().map(Occupant::to_nbt).collect()),
)];
if let Some(f) = self.flower {
out.push(("flower_pos", Tag::IntArray(f.to_vec())));
}
out
}
/// `addOccupant` (the bee's own tag, saved by the host): the hive keeps
/// the bee's flower, or now and then swaps its own for it. The host then
/// discards the bee.
pub fn add_occupant(
&mut self,
at: [i32; 3],
tag: Tag,
bee_flower: Option<[i32; 3]>,
host: &mut impl HiveHost,
) -> bool {
if self.bees.len() >= MAX_OCCUPANTS {
return false;
}
self.bees.push(Occupant::of(tag));
if let Some(f) = bee_flower
&& (self.flower.is_none() || host.random().next_boolean())
{
self.flower = Some(f);
}
let corner = at.map(f64::from);
host.sound("block.beehive.enter", corner);
true
}
/// `serverTick`: the bees whose time is up come out, then the hive
/// hums now and then while it holds any. `honey` is the hive state's
/// honey level as the tick starts (`None` without the property);
/// `facing` its front.
pub fn server_tick(
&mut self,
at: [i32; 3],
facing: [i32; 2],
honey: Option<i32>,
host: &mut impl HiveHost,
) {
let flower = self.flower;
let mut i = 0;
while i < self.bees.len() {
// BeeData.tick: ticksInHive++ > minTicksInHive.
let b = &mut self.bees[i];
let up = b.ticks_in_hive > b.min_ticks_in_hive;
b.ticks_in_hive += 1;
if up {
let status = if b.has_nectar() {
Release::HoneyDelivered
} else {
Release::BeeReleased
};
let occupant = b.clone();
if release(host, at, facing, honey, &occupant, status, flower).is_some() {
self.bees.remove(i);
continue;
}
}
i += 1;
}
if !self.bees.is_empty() && host.random().next_double() < 0.005 {
let hum = [
f64::from(at[0]) + 0.5,
f64::from(at[1]),
f64::from(at[2]) + 0.5,
];
host.sound("block.beehive.work", hum);
}
}
/// `releaseAllOccupants`: the ids of the bees let out.
pub fn release_all(
&mut self,
at: [i32; 3],
facing: [i32; 2],
honey: Option<i32>,
status: Release,
host: &mut impl HiveHost,
) -> Vec<u32> {
let flower = self.flower;
let mut out = Vec::new();
self.bees.retain(
|b| match release(host, at, facing, honey, b, status, flower) {
Some(id) => {
out.extend(id);
false
}
None => true,
},
);
out
}
}
/// `releaseOccupant`: `None` while the bee stays in, else the id of the bee
/// let out (`Some(None)` when the level refused it).
fn release(
host: &mut impl HiveHost,
at: [i32; 3],
facing: [i32; 2],
honey: Option<i32>,
occupant: &Occupant,
status: Release,
flower: Option<[i32; 3]>,
) -> Option<Option<u32>> {
let emergency = status == Release::Emergency;
if host.bees_stay_in_hive(at) && !emergency {
return None;
}
let blocked = host.blocked([at[0] + facing[0], at[1], at[2] + facing[1]]);
if blocked && !emergency {
return None;
}
// Occupant.createEntity: the tag without the ignored tags.
let mut tag = occupant.entity_data.clone();
if let Tag::Compound(c) = &mut tag {
strip_ignored(c);
let center = [at[0], at[1], at[2]].map(|v| Tag::Double((f64::from(v) + 0.5).to_bits()));
c.insert("Pos".into(), Tag::List(center.to_vec()));
}
let mut m = host.load(&tag)?;
m.no_gravity = true;
if m.species() == Species::Bee {
bee::set_hive(&mut m, Some(at));
// setBeeReleaseData: the time inside counts towards growing up and
// away from love.
let ticks = occupant.ticks_in_hive;
if !m.extra.age_locked {
let age = m.extra.age;
m.extra.age = if age < 0 {
(age + ticks).min(0)
} else if age > 0 {
(age - ticks).max(0)
} else {
age
};
}
m.extra.in_love = (m.extra.in_love - ticks).max(0);
if let Some(f) = flower
&& bee::get(&m).is_none_or(|b| b.flower.is_none())
&& host.random().next_float() < 0.9
{
bee::set_flower(&mut m, Some(f));
}
if status == Release::HoneyDelivered {
bee::drop_off_nectar(&mut m);
if let Some(level) = honey.filter(|&l| l < 5) {
let mut increase = if host.random().next_int_bound(100).unwrap_or(1) == 0 {
2
} else {
1
};
if level + increase > 5 {
increase -= 1;
}
host.set_honey_level(at, level + increase);
}
}
let delta = if blocked {
0.0
} else {
0.55 + f64::from(m.width() / 2.0)
};
let p = horizon_core::geometry::Vec3::new(
f64::from(at[0]) + 0.5 + delta * f64::from(facing[0]),
f64::from(at[1]) + 0.5 - f64::from(m.height() / 2.0),
f64::from(at[2]) + 0.5 + delta * f64::from(facing[1]),
);
m.position = p;
m.previous = p;
}
host.sound(
"block.beehive.exit",
[
f64::from(at[0]) + 0.5,
f64::from(at[1]) + 0.5,
f64::from(at[2]) + 0.5,
],
);
let id = m.id;
Some(host.add(m).then_some(id))
}
/// `CampfireBlock.isSmokeyPos`: a lit campfire up to five blocks below,
/// unless a block whose collision crosses the smoke's centre post comes
/// first (a lit campfire right under that block still counts).
pub fn smokey(w: &crate::mobs::MobWorld, at: [i32; 3]) -> bool {
let lit = |y: i32| {
w.has_tag("minecraft:campfires", w.block_name(at[0], y, at[2]))
&& w.prop(at[0], y, at[2], "lit") == Some("true")
};
for i in 1..=5 {
let y = at[1] - i;
if lit(y) {
return true;
}
// SHAPE_VIRTUAL_POST: Block.column(4, 0, 16), the middle quarter.
let (x0, z0) = (f64::from(at[0]), f64::from(at[2]));
let blocked = w.block_collision_boxes(at[0], y, at[2]).iter().any(|b| {
let (min, max) = (b.min_position(), b.max_position());
min.x < x0 + 0.625 && max.x > x0 + 0.375 && min.z < z0 + 0.625 && max.z > z0 + 0.375
});
if blocked {
return lit(y - 1);
}
}
false
}
/// `HorizontalDirectionalBlock.FACING` as an x/z step.
pub fn facing_step(facing: Option<&str>) -> [i32; 2] {
match facing {
Some("south") => [0, 1],
Some("west") => [-1, 0],
Some("east") => [1, 0],
_ => [0, -1],
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nbt_round_trips_in_vanilla_order() {
let tag = Tag::compound([
(
"bees",
Tag::List(vec![
Occupant::create(37).to_nbt(),
Occupant::create(0).to_nbt(),
]),
),
("flower_pos", Tag::IntArray(vec![1, -60, 3])),
]);
let hive = Beehive::from_nbt(&tag);
assert_eq!(hive.bees.len(), 2);
assert_eq!(hive.bees[0].ticks_in_hive, 37);
assert_eq!(hive.flower, Some([1, -60, 3]));
assert_eq!(Tag::compound(hive.to_nbt()), tag);
}
#[test]
fn a_bad_bee_drops_the_whole_list() {
let tag = Tag::compound([(
"bees",
Tag::List(vec![
Occupant::create(1).to_nbt(),
Tag::compound([("ticks_in_hive", Tag::Int(3))]),
]),
)]);
assert!(Beehive::from_nbt(&tag).bees.is_empty());
}
#[test]
fn going_in_strips_the_ignored_tags() {
let tag = Tag::compound([
("id", Tag::String("minecraft:bee".into())),
("UUID", Tag::IntArray(vec![1, 2, 3, 4])),
("Health", Tag::Float(10.0_f32.to_bits())),
("HasNectar", Tag::Byte(1)),
("hive_pos", Tag::IntArray(vec![0, 0, 0])),
]);
let o = Occupant::of(tag);
assert_eq!(o.min_ticks_in_hive, 2400);
assert!(o.entity_data.get("UUID").is_none());
assert!(o.entity_data.get("hive_pos").is_none());
assert!(o.entity_data.get("Health").is_some());
}
}
+11 -3
View File
@@ -68,6 +68,8 @@ pub enum BlockEntity {
Crafter(Crafter),
/// `SpawnerBlockEntity` (`crate::mobs::spawner`).
Spawner(Box<crate::mobs::spawner::Spawner>),
/// `BeehiveBlockEntity` of beehives and bee nests (`crate::beehive`).
Beehive(Box<crate::beehive::Beehive>),
}
/// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag
/// and the ticks left in the crafting animation.
@@ -185,6 +187,9 @@ impl BlockEntity {
if name == "minecraft:spawner" {
return Some(Self::Spawner(Box::default()));
}
if name == "minecraft:beehive" || name == "minecraft:bee_nest" {
return Some(Self::Beehive(Box::default()));
}
if name == "minecraft:lectern" {
return Some(Self::Lectern(Lectern::default()));
}
@@ -261,6 +266,7 @@ impl BlockEntity {
Self::Crafter(_) => "minecraft:crafter",
Self::CreakingHeart(_) => "minecraft:creaking_heart",
Self::Spawner(_) => "minecraft:mob_spawner",
Self::Beehive(_) => "minecraft:beehive",
}
}
pub fn contents(&self) -> Vec<ItemStack> {
@@ -270,7 +276,9 @@ impl BlockEntity {
Self::Brewing(b) => b.items.iter().flatten().cloned().collect(),
Self::Sign(_) => Vec::new(),
Self::Jukebox(j) => j.record.iter().cloned().collect(),
Self::Beacon(_) | Self::CreakingHeart(_) | Self::Spawner(_) => Vec::new(),
Self::Beacon(_) | Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => {
Vec::new()
}
Self::Lectern(l) => l.book.iter().cloned().collect(),
Self::Sculk(_) => Vec::new(),
Self::Banner(_) => Vec::new(),
@@ -289,7 +297,7 @@ impl BlockEntity {
| Self::Sculk(_)
| Self::Banner(_) => &[],
Self::Crafter(c) => &c.items,
Self::CreakingHeart(_) | Self::Spawner(_) => &[],
Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => &[],
}
}
pub fn slots_mut(&mut self) -> &mut [Option<ItemStack>] {
@@ -304,7 +312,7 @@ impl BlockEntity {
| Self::Sculk(_)
| Self::Banner(_) => &mut [],
Self::Crafter(c) => &mut c.items,
Self::CreakingHeart(_) | Self::Spawner(_) => &mut [],
Self::CreakingHeart(_) | Self::Spawner(_) | Self::Beehive(_) => &mut [],
}
}
}
+16 -2
View File
@@ -8,6 +8,7 @@ mod armor_stands;
mod backdrop;
mod banners;
mod beacon;
mod beehives;
mod block_entity_anims;
mod blockctl;
mod boats;
@@ -2150,6 +2151,10 @@ impl Game<'_> {
self.pending.record_saved(pos, &tag);
}
self.creaking_heart_broken(pos);
let hive = match self.world.block_entities.get(&key) {
Some(BlockEntity::Beehive(h)) => self.hive_state(pos).map(|s| ((**h).clone(), s)),
_ => None,
};
// playerWillDestroy and Level.removeBlock through the vanilla behaviour
// library: the block entity's side effects (containers spill), neighbour
// and shape updates, and the destroy event (particles, sound).
@@ -2199,6 +2204,12 @@ impl Game<'_> {
self.pop_resource(pos, d);
}
}
// BeehiveBlock.playerDestroy: silk touch keeps the bees in.
if let Some((hive, (honey, facing))) = hive
&& !silk
{
self.hive_broken_by_player(pos, hive, honey, facing);
}
// SpawnerBlock.spawnAfterBreak pops its experience whatever the tool.
let xp = if silk && &*facts.name != "minecraft:spawner" {
0
@@ -3793,7 +3804,8 @@ impl Game<'_> {
| BlockEntity::Sculk(_)
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_)
| BlockEntity::Spawner(_),
| BlockEntity::Spawner(_)
| BlockEntity::Beehive(_),
) => {}
None => {
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
@@ -4042,7 +4054,8 @@ impl Game<'_> {
| BlockEntity::Sculk(_)
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_)
| BlockEntity::Spawner(_),
| BlockEntity::Spawner(_)
| BlockEntity::Beehive(_),
) => {}
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
None => {
@@ -5549,6 +5562,7 @@ impl Game<'_> {
self.tick_beacons();
self.tick_creaking_hearts()?;
self.tick_spawners()?;
self.tick_beehives();
let mut lit_changes = Vec::new();
for (pos, entity) in self.world.block_entities.iter_mut() {
if let BlockEntity::Furnace(f) = entity
+238
View File
@@ -0,0 +1,238 @@
//! Beehives and bee nests in the game (`crate::beehive` holds their logic):
//! their server tick, bees going in, and the bees let out, angry, when a
//! player breaks the hive or fire reaches it.
use super::Game;
use horizon_client::{
beehive::{self, Beehive, HiveHost, Release},
containers::BlockEntity,
mobs::{Mob, Who, bee},
};
use horizon_core::{
geometry::{Aabb, Vec3},
random::{LegacyRandom, RandomSource},
};
use horizon_world::{nbt::Tag, registry::BlockStateId};
struct GameHive<'g, 'a> {
game: &'g mut Game<'a>,
}
impl HiveHost for GameHive<'_, '_> {
fn random(&mut self) -> &mut LegacyRandom {
&mut self.game.world.random
}
fn bees_stay_in_hive(&self, _at: [i32; 3]) -> bool {
bee::bees_stay_in_hive(&self.game.mob_world_base(&[]))
}
fn blocked(&self, at: [i32; 3]) -> bool {
!self
.game
.mob_world_base(&[])
.block_collision_boxes(at[0], at[1], at[2])
.is_empty()
}
fn set_honey_level(&mut self, at: [i32; 3], level: i32) {
let state = self.game.world.block(at[0], at[1], at[2]);
if let Some(state) = self.game.hive_with_honey(state, level) {
let _ = self.game.level_set(at, state);
}
}
fn load(&mut self, tag: &Tag) -> Option<Mob> {
let kind = horizon_client::entity_nbt::kind(tag)?;
if !self
.game
.res
.mob_data
.entity_has("minecraft:beehive_inhabitors", &kind)
{
return None;
}
let id = self.game.load_mob(tag.clone(), None)?;
let i = self.game.mobs.iter().position(|m| m.id == id)?;
Some(self.game.mobs.remove(i))
}
fn add(&mut self, m: Mob) -> bool {
self.game.mobs.push(m);
true
}
fn sound(&mut self, name: &'static str, at: [f64; 3]) {
self.game
.audio
.play(&format!("minecraft:{name}"), Some(at), 1.0, 1.0);
}
}
impl Game<'_> {
fn hive_with_honey(&self, state: BlockStateId, level: i32) -> Option<BlockStateId> {
let registry = self.res.assets.registry;
let mut s = registry.state(state)?.clone();
s.properties
.insert("honey_level".to_owned(), level.to_string());
registry.resolve(&s).ok()
}
/// The hive's honey level and front, from its block state.
pub(super) fn hive_state(&self, at: [i32; 3]) -> Option<(Option<i32>, [i32; 2])> {
let state = self.world.block(at[0], at[1], at[2]);
let name = &self.res.facts.get(state).name;
if !self
.res
.items
.block_tags
.get("minecraft:beehives")
.is_some_and(|t| t.contains(&**name))
{
return None;
}
let props = &self.res.assets.registry.state(state)?.properties;
let honey = props.get("honey_level").and_then(|v| v.parse().ok());
let facing = beehive::facing_step(props.get("facing").map(String::as_str));
Some((honey, facing))
}
/// `BeehiveBlockEntity.serverTick` for every hive, after an emergency
/// exit for those with fire beside them (`BeehiveBlock.updateShape`).
pub(super) fn tick_beehives(&mut self) {
let mut keys: Vec<(i32, i32, i32)> = self
.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::Beehive(_)))
.map(|(k, _)| *k)
.collect();
keys.sort_unstable();
for key in keys {
let at = [key.0, key.1, key.2];
let Some((honey, facing)) = self.hive_state(at) else {
continue;
};
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key)
else {
continue;
};
let fire = [
[1, 0, 0],
[-1, 0, 0],
[0, 1, 0],
[0, -1, 0],
[0, 0, 1],
[0, 0, -1],
]
.iter()
.any(|d| {
let state = self.world.block(at[0] + d[0], at[1] + d[1], at[2] + d[2]);
&*self.res.facts.get(state).name == "minecraft:fire"
});
let mut host = GameHive { game: self };
if fire && !hive.bees.is_empty() {
hive.release_all(at, facing, honey, Release::Emergency, &mut host);
}
hive.server_tick(at, facing, honey, &mut host);
self.world
.block_entities
.insert(key, BlockEntity::Beehive(hive));
}
}
/// `BeehiveBlockEntity.addOccupant` for a bee its `BeeEnterHiveGoal`
/// sent in: off its lead, its tag stored, the bee gone.
pub(super) fn bee_enter_hive(&mut self, mob: u32, at: [i32; 3]) {
let key = (at[0], at[1], at[2]);
let Some(i) = self
.mobs
.iter()
.position(|m| m.id == mob && m.alive() && !m.removed)
else {
return;
};
if !matches!(self.world.block_entities.get(&key), Some(BlockEntity::Beehive(h)) if !h.full())
{
return;
}
if self.mobs[i].extra.leash.is_some() {
self.break_leash(mob, true, false);
self.mobs[i].extra.leash = None;
}
self.mobs[i].extra.mount = None;
let tag = self.mob_tree_nbt(i);
let flower = bee::get(&self.mobs[i]).and_then(|b| b.flower);
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) else {
return;
};
let stored = hive.add_occupant(at, tag, flower, &mut GameHive { game: self });
self.world
.block_entities
.insert(key, BlockEntity::Beehive(hive));
if stored && let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
m.removed = true;
}
}
/// `BeehiveBlockEntity.emptyAllLivingFromHive` with no player about.
pub(super) fn empty_hive(&mut self, at: [i32; 3], facing: [i32; 2], status: Release) {
let key = (at[0], at[1], at[2]);
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) else {
return;
};
hive.release_all(at, facing, None, status, &mut GameHive { game: self });
self.world
.block_entities
.insert(key, BlockEntity::Beehive(hive));
}
/// `BeehiveBlock.playerDestroy` without silk touch: the bees come out
/// angry at the player unless smoke calms them, then
/// `angerNearbyBees`.
pub(super) fn hive_broken_by_player(
&mut self,
at: [i32; 3],
mut hive: Beehive,
honey: Option<i32>,
facing: [i32; 2],
) {
let released = hive.release_all(
at,
facing,
honey,
Release::Emergency,
&mut GameHive { game: self },
);
let sedated = beehive::smokey(&self.mob_world_base(&[]), at);
if let Some(p) = self.player_view().map(|p| p.position) {
for m in self.mobs.iter_mut().filter(|m| released.contains(&m.id)) {
if m.distance_sqr(p) <= 16.0 {
if sedated {
bee::set_stay_out_of_hive_countdown(m);
} else {
m.ai.target = Some(Who::Player);
}
}
}
}
self.anger_nearby_bees(at);
}
/// `BeehiveBlock.angerNearbyBees`: bees within 8 blocks (6 up and down)
/// without a target go for a player in the same box.
fn anger_nearby_bees(&mut self, at: [i32; 3]) {
let min = Vec3::new(
f64::from(at[0]) - 8.0,
f64::from(at[1]) - 6.0,
f64::from(at[2]) - 8.0,
);
let area = Aabb::new(min, Vec3::new(min.x + 17.0, min.y + 13.0, min.z + 17.0));
if !self
.player_view()
.is_some_and(|p| p.bounds.intersects(area))
{
return;
}
let mut bees: Vec<usize> = (0..self.mobs.len())
.filter(|&i| {
let m = &self.mobs[i];
m.species() == horizon_client::mobs::Species::Bee
&& !m.removed
&& m.bounds().intersects(area)
})
.collect();
bees.retain(|&i| self.mobs[i].ai.target.is_none());
for i in bees {
// Util.getRandom over the one player.
let _ = self.world.random.next_int_bound(1);
self.mobs[i].ai.target = Some(Who::Player);
}
}
}
@@ -884,6 +884,7 @@ impl Game<'_> {
self.golem_chest_slot(chest, slot, stack)
}
MobEvent::BecomeStatue { mob } => self.golem_become_statue(mob),
MobEvent::EnterHive { mob, hive } => self.bee_enter_hive(mob, hive),
MobEvent::Gift { target, item } => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == target)
&& m.saddle_item().is_none()
+13 -1
View File
@@ -1552,10 +1552,11 @@ impl Game<'_> {
&& let Some(level) = honey
&& level >= 5
{
// releaseBeesAndResetHoneyLevel (the bees themselves are not modelled).
// releaseBeesAndResetHoneyLevel.
if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) {
self.level_set([target.0, target.1, target.2], reset)?;
}
self.dispenser_empty_hive(target, state);
let bottle = ItemStack::new("minecraft:honey_bottle", 1);
self.post_block_game_event("minecraft:fluid_pickup", [pos.0, pos.1, pos.2], None, None);
return Ok((
@@ -1624,6 +1625,16 @@ impl Game<'_> {
}
Ok((Some(stack), FAIL))
}
/// The bees of a hive a dispenser harvested come out (`BEE_RELEASED`:
/// not at night nor in the rain), through the front of its old state.
fn dispenser_empty_hive(&mut self, target: Pos, old: BlockStateId) {
let facing = self.prop(old, "facing");
self.empty_hive(
[target.0, target.1, target.2],
horizon_client::beehive::facing_step(facing.as_deref()),
horizon_client::beehive::Release::BeeReleased,
);
}
fn shear_beehive(&mut self, target: Pos) -> Result<bool> {
let state = self.block_at(target);
let name = self.dispenser_block_name(target);
@@ -1652,6 +1663,7 @@ impl Game<'_> {
if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) {
self.level_set(p, reset)?;
}
self.dispenser_empty_hive(target, state);
self.post_block_game_event("minecraft:shear", p, None, None);
Ok(true)
}
+1
View File
@@ -13,6 +13,7 @@ pub mod audio;
pub mod auth;
pub mod auto_jump;
pub mod banner;
pub mod beehive;
pub mod benchmark;
pub mod biome;
pub mod block_entity_anim;
+6
View File
@@ -847,6 +847,12 @@ pub enum MobEvent {
chest: [i32; 3],
open: bool,
},
/// `BeeEnterHiveGoal.start`: the bee goes into its hive (the host stores
/// its tag with `BeehiveBlockEntity.addOccupant` and discards it).
EnterHive {
mob: u32,
hive: [i32; 3],
},
/// `CopperGolem.turnToStatue`.
BecomeStatue {
mob: u32,
+130 -21
View File
@@ -1,9 +1,11 @@
//! 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.
//! once and dying of it, and the hive and flower bookkeeping: finding a hive
//! with room nearby (`BeeLocateHiveGoal`), flying home at night, in the rain
//! or with nectar (`BeeGoToHiveGoal`) and going in (`BeeEnterHiveGoal`, done
//! by the host: [`MobEvent::EnterHive`]); the hive lets them out
//! (`crate::beehive`).
use super::{
Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who,
control::{LookKind, MoveKind},
@@ -47,6 +49,8 @@ pub struct Bee {
/// The cooldowns `ValidateHiveGoal` and `ValidateFlowerGoal` draw when built.
pub validate_hive_cooldown: i32,
pub validate_flower_cooldown: i32,
/// `BeeGoToHiveGoal.blacklistedTargets`: the last three hives it gave up on.
pub hive_blacklist: Vec<[i32; 3]>,
}
impl Default for Bee {
fn default() -> Self {
@@ -68,6 +72,7 @@ impl Default for Bee {
pollinating: false,
validate_hive_cooldown: 0,
validate_flower_cooldown: 0,
hive_blacklist: Vec::new(),
}
}
}
@@ -361,12 +366,33 @@ fn closer_than(m: &Mob, p: [i32; 3], dist: i32) -> bool {
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
/// `Bee.getBeehiveBlockEntity`: the hive's block entity, unless too far.
fn hive_entity<'a>(m: &Mob, w: &'a MobWorld) -> Option<&'a crate::beehive::Beehive> {
let h = get(m)?.hive?;
if too_far(m, h) {
return None;
}
match w.world.block_entities.get(&(h[0], h[1], h[2])) {
Some(crate::containers::BlockEntity::Beehive(hive)) => Some(hive),
_ => None,
}
}
fn hive_valid(m: &Mob, w: &MobWorld) -> bool {
hive_entity(m, w).is_some()
}
/// `BeehiveBlockEntity.isFireNearby`: fire (not soul fire) next to the hive.
fn hive_near_fire(m: &Mob, w: &MobWorld) -> bool {
let Some(h) = get(m).and_then(|b| b.hive).filter(|_| hive_valid(m, w)) else {
return false;
};
(-1..=1).any(|dx| {
(-1..=1).any(|dy| {
(-1..=1).any(|dz| w.block_name(h[0] + dx, h[1] + dy, h[2] + dz) == "minecraft:fire")
})
})
}
/// `EnvironmentAttributes.BEES_STAY_IN_HIVE`: the overworld's night, or rain.
fn bees_stay_in_hive(w: &MobWorld) -> bool {
pub 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
}
@@ -379,8 +405,26 @@ fn wants_to_enter_hive(m: &Mob, w: &MobWorld) -> bool {
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)
(has_nectar(m) || tired_of_looking_for_nectar(m) || bees_stay_in_hive(w))
&& !hive_near_fire(m, w)
}
/// `Bee.setHivePos`.
pub fn set_hive(m: &mut Mob, hive: Option<[i32; 3]>) {
st(m).hive = hive;
}
/// `Bee.setSavedFlowerPos`.
pub fn set_flower(m: &mut Mob, flower: Option<[i32; 3]>) {
st(m).flower = flower;
}
/// `Bee.dropOffNectar`.
pub fn drop_off_nectar(m: &mut Mob) {
set_has_nectar(m, false);
st(m).crops_grown = 0;
}
/// `Bee.setStayOutOfHiveCountdown`, which in 26.3 only resets the time
/// without nectar.
pub fn set_stay_out_of_hive_countdown(m: &mut Mob) {
st(m).ticks_without_nectar = 0;
}
fn drop_hive(m: &mut Mob) {
let b = st(m);
@@ -527,7 +571,7 @@ impl Goal for BecomeAngryTarget {
}
}
/// `BeeEnterHiveGoal`: into the hive beside it (none is ever valid yet).
/// `BeeEnterHiveGoal`: into the hive beside it, or forget it when full.
#[derive(Clone, Debug)]
struct EnterHive;
impl Goal for EnterHive {
@@ -544,12 +588,24 @@ impl Goal for EnterHive {
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);
let mut enter = false;
if close && wants_to_enter_hive(m, cx.w) {
match hive_entity(m, cx.w).map(|h| h.full()) {
Some(false) => enter = true,
Some(true) => st(m).hive = None,
None => {}
}
}
enter && 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(hive) = get(m).and_then(|b| b.hive).filter(|_| hive_valid(m, cx.w)) {
cx.events.push(MobEvent::EnterHive { mob: m.id, hive });
}
}
}
/// `ValidateHiveGoal`: now and then, forget a hive that is gone.
@@ -771,7 +827,8 @@ impl Goal for Pollinate {
}
}
/// `BeeLocateHiveGoal`: the nearest bee home with room (none yet).
/// `BeeLocateHiveGoal`: the nearest bee home with room within 20 blocks,
/// skipping the ones `BeeGoToHiveGoal` gave up on (unless that is all).
#[derive(Clone, Debug)]
struct LocateHive;
impl Goal for LocateHive {
@@ -791,17 +848,49 @@ impl Goal for LocateHive {
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.
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
st(m).hive_cooldown = 200;
let hives = hives_with_space(m, cx.w);
let b = st(m);
let pick = hives
.iter()
.find(|h| !b.hive_blacklist.contains(h))
.copied();
if pick.is_none() && !hives.is_empty() {
b.hive_blacklist.clear();
}
b.hive = pick.or_else(|| hives.first().copied()).or(b.hive);
}
}
/// `findNearbyHivesWithSpace`: the bee homes (`PoiTypeTags.BEE_HOME`)
/// within 20 blocks whose hive has room, nearest first.
fn hives_with_space(m: &Mob, w: &MobWorld) -> Vec<[i32; 3]> {
let here = block_pos(m);
let dist = |p: &[i32; 3]| {
let d = |i: usize| i64::from(p[i] - here[i]);
d(0) * d(0) + d(1) * d(1) + d(2) * d(2)
};
let mut hives: Vec<[i32; 3]> = w
.world
.block_entities
.iter()
.filter_map(|(&(x, y, z), e)| match e {
crate::containers::BlockEntity::Beehive(h) if !h.full() => Some([x, y, z]),
_ => None,
})
.filter(|p| {
dist(p) <= 20 * 20 && w.has_tag("minecraft:beehives", w.block_name(p[0], p[1], p[2]))
})
.collect();
hives.sort_by_key(|p| (dist(p), *p));
hives
}
/// `BeeGoToHiveGoal`: home when it wants to go in.
#[derive(Clone, Debug, Default)]
struct GoToHive {
travelling: i32,
blacklist: Vec<[i32; 3]>,
last_path: Option<super::path::Path>,
stuck: i32,
}
@@ -815,10 +904,11 @@ impl GoToHive {
.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);
let b = st(m);
if let Some(h) = b.hive {
b.hive_blacklist.push(h);
while b.hive_blacklist.len() > 3 {
b.hive_blacklist.remove(0);
}
}
drop_hive(m);
@@ -1037,8 +1127,27 @@ impl Goal for Wander {
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();
// Back towards a valid hive farther than 24 blocks, else ahead.
let far_hive = get(m)
.and_then(|b| b.hive)
.filter(|&h| hive_valid(m, cx.w) && !closer_than(m, h, 24));
let dir = match far_hive {
Some(h) => {
let v = [
f64::from(h[0]) + 0.5 - m.position.x,
f64::from(h[1]) + 0.5 - m.position.y,
f64::from(h[2]) + 0.5 - m.position.z,
];
// Vec3.normalize.
let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
if len < 1.0E-5 {
[0.0; 3]
} else {
v.map(|c| c / len)
}
}
None => 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)
+2
View File
@@ -527,6 +527,7 @@ pub fn encode_block_entity(
}
}
BlockEntity::Spawner(s) => entries.extend(s.save()),
BlockEntity::Beehive(h) => entries.extend(h.to_nbt()),
}
Tag::compound(entries)
}
@@ -655,6 +656,7 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_) => {}
BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag),
BlockEntity::Beehive(h) => **h = crate::beehive::Beehive::from_nbt(tag),
}
Some((pos, entity))
}
@@ -585,6 +585,7 @@ public final class VanillaMobAiOracle {
}
}
case "inlove" -> ((net.minecraft.world.entity.animal.Animal) mob).setInLoveTime(600);
case "nectar" -> method(net.minecraft.world.entity.animal.bee.Bee.class, "setHasNectar", boolean.class).invoke(mob, true);
case "tame" -> { if (mob instanceof net.minecraft.world.entity.animal.equine.AbstractHorse horse) horse.setTamed(true); }
case "strength" -> method(net.minecraft.world.entity.animal.equine.Llama.class, "setStrength", int.class)
.invoke(mob, Integer.parseInt(v));
@@ -615,20 +616,7 @@ 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));
}
if (mob instanceof net.minecraft.world.entity.animal.bee.Bee bee) seedBee(bee);
@SuppressWarnings("unchecked")
Map<Object, Sensor<?>> sensors = (Map<Object, Sensor<?>>) get(brain, "sensors");
for (Sensor<?> sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom());
@@ -748,14 +736,19 @@ public final class VanillaMobAiOracle {
if (e.isRemoved()) continue;
level.tickNonPassenger(e);
}
if (!heartPositions.isEmpty()) level.tickBlockEntities();
if (s.blocks.stream().anyMatch(Server::isHive)) {
// A bee leaving its hive takes the id the probe gives it, 100000 + its index
// (goals run in full on ticks where tickCount + id is even).
((java.util.concurrent.atomic.AtomicInteger) field(ServerLevel.class, "ENTITY_COUNTER").get(null)).set(100000 + ENTS.size() - 1);
level.tickBlockEntities();
} else if (!heartPositions.isEmpty()) level.tickBlockEntities();
managerTick.invoke(manager);
// Villagers the tick spawned (babies) and a heart's creakings tick from the next
// one, in the order they were added, with a seeded random of their own. Other
// newcomers (animal babies, dropped items) are left out, as the probe leaves them.
List<Entity> fresh = new ArrayList<>();
for (Entity e : level.getAllEntities())
if (!LABELS.containsKey(e) && (e instanceof Villager || created.contains(e))) fresh.add(e);
if (!LABELS.containsKey(e) && (e instanceof Villager || e instanceof net.minecraft.world.entity.animal.bee.Bee || created.contains(e))) fresh.add(e);
fresh.sort(java.util.Comparator.comparingInt(Entity::getId));
for (Entity e : fresh) {
int index = ENTS.size();
@@ -779,6 +772,8 @@ public final class VanillaMobAiOracle {
mob.yHeadRotO = mob.getYRot();
if (tracing(s)) field(Entity.class, "random").set(mob, new TracingRandom(0L, TRACE, index));
mob.getRandom().setSeed(seed);
// A bee out of a hive: its constructor drew from an unseeded random.
if (mob instanceof net.minecraft.world.entity.animal.bee.Bee bee) seedBee(bee);
@SuppressWarnings("unchecked")
Map<Object, Sensor<?>> sensors = (Map<Object, Sensor<?>>) get(mob.getBrain(), "sensors");
for (Sensor<?> sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom());
@@ -791,6 +786,7 @@ public final class VanillaMobAiOracle {
for (int i = 0; i < ENTS.size(); i++) print(t, i, ENTS.get(i));
for (BlockPos h : heartPositions) printHeart(t, level, h);
for (String[] b : s.blocks) if (b[0].equals("chest")) printChest(t, s, level, b);
for (String[] b : s.blocks) if (isHive(b)) printHive(t, level, b);
for (String sound : SOUNDS) out.println(t + " sound " + sound);
for (var w : watched.entrySet()) {
BlockState now = level.getBlockState(w.getKey());
@@ -812,6 +808,44 @@ public final class VanillaMobAiOracle {
out.flush();
}
/**
* A bee's constructor draws, made again with its seeded random: the validate goals'
* cooldowns (registerGoals), then the flower cooldown's initialiser.
*/
static void seedBee(net.minecraft.world.entity.animal.bee.Bee bee) throws Exception {
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));
}
/** A hive's honey level and bees (ticks inside / ticks to stay). */
static void printHive(int t, ServerLevel level, String[] b) {
BlockPos at = new BlockPos(Integer.parseInt(b[1]), Integer.parseInt(b[2]), Integer.parseInt(b[3]));
if (!(level.getBlockEntity(at) instanceof net.minecraft.world.level.block.entity.BeehiveBlockEntity hive)) return;
net.minecraft.nbt.CompoundTag tag = hive.saveWithoutMetadata(level.registryAccess());
StringBuilder bees = new StringBuilder();
for (var bee : tag.getListOrEmpty("bees")) {
net.minecraft.nbt.CompoundTag c = (net.minecraft.nbt.CompoundTag) bee;
if (!bees.isEmpty()) bees.append(',');
bees.append(c.getIntOr("ticks_in_hive", 0)).append('/').append(c.getIntOr("min_ticks_in_hive", 0));
}
BlockState state = level.getBlockState(at);
out.println(t + " hive " + b[1] + "," + b[2] + "," + b[3] + " honey "
+ (state.hasProperty(net.minecraft.world.level.block.BeehiveBlock.HONEY_LEVEL) ? state.getValue(net.minecraft.world.level.block.BeehiveBlock.HONEY_LEVEL) : -1)
+ " bees " + (bees.isEmpty() ? "-" : bees) + " flower " + tag.getIntArray("flower_pos").map(p -> p[0] + "," + p[1] + "," + p[2]).orElse("-"));
}
static boolean isHive(String[] b) {
return b[0].equals("block") && (b[4].startsWith("minecraft:beehive") || b[4].startsWith("minecraft:bee_nest"));
}
/** The random seed of the entity a scenario spawned at this index. */
static long spawnSeed(int index) { return 1000L + 7919L * index; }
+12 -2
View File
@@ -250,6 +250,13 @@ def scenarios():
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'])
# Bees and their hive: home at night and in the rain (BeeLocateHiveGoal, BeeGoToHiveGoal,
# BeeEnterHiveGoal), out again once the morning comes, and nectar turned into honey.
HIVE = 'block 4 -60 0 minecraft:beehive[facing=west,honey_level=0]'
add('bee_hive_night', 300, [HIVE, 'mob minecraft:bee 0.5 -58 0.5 0 161 persistent'], 'time=13000')
add('bee_hive_rain', 300, [HIVE, 'mob minecraft:bee 0.5 -58 0.5 0 162 persistent'], 'rain')
add('bee_hive_morning', 1000, [HIVE, 'mob minecraft:bee 0.5 -58 0.5 0 163 persistent'], 'time=22900 daycycle')
add('bee_hive_honey', 2600, [HIVE, 'mob minecraft:bee 0.5 -58 0.5 0 164 persistent nectar'])
return s
@@ -304,6 +311,9 @@ def parse(path):
if parts[1] == 'heart':
cur.setdefault('hearts', {}).setdefault(t, []).append(line.split(' ', 2)[2])
continue
if parts[1] == 'hive':
cur.setdefault('hives', {}).setdefault(t, []).append(parts[2])
continue
if parts[1] == 'chest':
cur.setdefault('chests', {}).setdefault(t, []).append(parts[2])
continue
@@ -400,8 +410,8 @@ def compare(vanilla, rust, fields=None):
report.append(f'{name}: hearts differ at tick {t}: vanilla {v.get("hearts", {}).get(t)} | horizon {r.get("hearts", {}).get(t)}')
clean = False
break
# Sounds, watched block changes and chest contents: first differing tick.
for kind in ('sounds', 'blocks', 'chests'):
# Sounds, watched block changes, chest contents and hives: first differing tick.
for kind in ('sounds', 'blocks', 'chests', 'hives'):
va, ra = v.get(kind, {}), r.get(kind, {})
for t in sorted(set(va) | set(ra)):
if va.get(t, []) != ra.get(t, []):