Give villagers a daily schedule

Villagers claim a free bed and a bell, work at their job site by day
(work sounds, and up to two restocks a day with demand catch-up), meet
at the bell in the evening and sleep in their bed at night, lying as
vanilla draws sleepers. They wake at dawn, when hurt or when the bed
goes. Memories, restock counts and the last restock are saved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-09 11:21:51 +02:00
parent 2b664b4c4e
commit 78165ecdf6
9 changed files with 497 additions and 51 deletions
+38 -23
View File
@@ -266,10 +266,12 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
("level", Tag::Int(i32::from(m.extra.variant3.max(1)))),
]);
map.insert("VillagerData".into(), data);
let xp = m.extra.trade.as_ref().map_or(0, |t| t.xp);
map.insert("Xp".into(), Tag::Int(xp));
let t = m.extra.trade.as_deref().cloned().unwrap_or_default();
map.insert("Xp".into(), Tag::Int(t.xp));
map.insert("LastRestock".into(), Tag::Long(t.last_restock));
map.insert("RestocksToday".into(), Tag::Int(t.restocks_today));
put_offers(map, m);
put_job_site(map, m.extra.home);
put_memories(map, m);
}
"minecraft:wandering_trader" => put_offers(map, m),
"minecraft:allay" => {
@@ -999,19 +1001,25 @@ fn put_offers(map: &mut Compound, m: &Mob) {
Tag::compound([("Recipes", Tag::List(recipes))]),
);
}
/// The villager brain's `job_site` memory.
fn put_job_site(map: &mut Compound, site: Option<[i32; 3]>) {
let Some(p) = site else { return };
let pos = Tag::compound([
("dimension", string("minecraft:overworld")),
("pos", Tag::IntArray(p.to_vec())),
]);
/// The villager brain's `job_site`, `home` and `meeting_point` memories.
fn put_memories(map: &mut Compound, m: &Mob) {
let memories: Vec<(&str, Tag)> = [
("minecraft:job_site", m.extra.home),
("minecraft:home", m.extra.bed),
("minecraft:meeting_point", m.extra.meeting),
]
.into_iter()
.filter_map(|(key, p)| {
let pos = Tag::compound([
("dimension", string("minecraft:overworld")),
("pos", Tag::IntArray(p?.to_vec())),
]);
Some((key, Tag::compound([("value", pos)])))
})
.collect();
map.insert(
"Brain".into(),
Tag::compound([(
"memories",
Tag::compound([("minecraft:job_site", Tag::compound([("value", pos)]))]),
)]),
Tag::compound([("memories", Tag::compound(memories))]),
);
}
fn read_villager(m: &mut Mob, tag: &Tag) {
@@ -1029,15 +1037,19 @@ fn read_villager(m: &mut Mob, tag: &Tag) {
.unwrap_or(0) as u8;
m.extra.variant3 = number(data.get("level")).unwrap_or(1).clamp(1, 5) as u8;
}
m.extra.home = tag
.get("Brain")
.and_then(|b| b.get("memories"))
.and_then(|b| b.get("minecraft:job_site"))
.and_then(|j| j.get("value"))
.and_then(|v| match v.get("pos") {
Some(Tag::IntArray(a)) if a.len() == 3 => Some([a[0], a[1], a[2]]),
_ => None,
});
let memory = |key: &str| {
tag.get("Brain")
.and_then(|b| b.get("memories"))
.and_then(|b| b.get(key))
.and_then(|j| j.get("value"))
.and_then(|v| match v.get("pos") {
Some(Tag::IntArray(a)) if a.len() == 3 => Some([a[0], a[1], a[2]]),
_ => None,
})
};
m.extra.home = memory("minecraft:job_site");
m.extra.bed = memory("minecraft:home");
m.extra.meeting = memory("minecraft:meeting_point");
let Some(Tag::List(recipes)) = tag.get("Offers").and_then(|o| o.get("Recipes")) else {
return;
};
@@ -1066,6 +1078,9 @@ fn read_villager(m: &mut Mob, tag: &Tag) {
m.extra.trade = Some(Box::new(Trader {
xp: number(tag.get("Xp")).unwrap_or(0) as i32,
offers,
last_restock: number(tag.get("LastRestock")).unwrap_or(0),
restocks_today: number(tag.get("RestocksToday")).unwrap_or(0) as i32,
check_day: 0,
}));
}
@@ -112,6 +112,9 @@ fn seen(m: &Mob) -> Seen {
job: (m.species() == Species::Villager)
.then_some(m.extra.home)
.flatten(),
bed: (m.species() == Species::Villager)
.then_some(m.extra.bed)
.flatten(),
}
}
impl Game<'_> {
@@ -248,6 +251,8 @@ impl Game<'_> {
"goals": m.ai.goals.running_names(),
"held": m.extra.main_hand.as_deref(),
"ints": m.extra.ints,
"pois": [m.extra.home, m.extra.bed, m.extra.meeting],
"profession": m.extra.variant2,
"targets": m.ai.targets.running_names(),
"path": m.ai.nav.path.as_ref().map(|p| p.nodes.len() - p.next.min(p.nodes.len())),
"on_ground": m.on_ground,
@@ -366,6 +371,7 @@ impl Game<'_> {
let (rain, thunder) = self.world.weather.levels(1.0);
MobWorld {
world: &self.world,
registry: self.res.assets.registry,
facts: &self.res.facts,
collision: self.collision,
data: &self.res.mob_data,
+7 -5
View File
@@ -142,7 +142,10 @@ impl Game<'_> {
self.new_offers(profession, variant, level)
}
};
self.mobs[index].extra.trade = Some(Box::new(merchant::Trader { xp: 0, offers }));
self.mobs[index].extra.trade = Some(Box::new(merchant::Trader {
offers,
..Default::default()
}));
}
let m = &self.mobs[index];
let trade = m.extra.trade.as_deref().cloned().unwrap_or_default();
@@ -184,10 +187,9 @@ impl Game<'_> {
if state.progress() {
m.extra.variant3 = state.level.clamp(1, 5) as u8;
}
m.extra.trade = Some(Box::new(merchant::Trader {
xp: state.xp,
offers: state.offers.clone(),
}));
let trade = m.extra.trade.get_or_insert_default();
trade.xp = state.xp;
trade.offers = state.offers.clone();
}
/// Opens a merchant menu for a villager (or a generated one for tests).
pub(super) fn open_merchant(&mut self, profession: &str, variant: &str, level: i32) {
+69
View File
@@ -53,6 +53,49 @@ pub const PROFESSIONS: &[&str] = &[
pub struct Trader {
pub xp: i32,
pub offers: Vec<MerchantOffer>,
/// `lastRestockGameTime`, `numberOfRestocksToday` and `lastRestockCheckDay`.
pub last_restock: i64,
pub restocks_today: i32,
pub check_day: i64,
}
impl Trader {
fn update_demand(&mut self) {
for o in &mut self.offers {
o.update_demand();
}
}
/// `Villager.shouldRestock`.
pub fn should_restock(&mut self, game_time: i64, day: i64) -> bool {
let mut new_day = game_time > self.last_restock + 12000;
new_day |= self.check_day > 0 && day > self.check_day;
self.check_day = day;
if new_day {
self.last_restock = game_time;
// resetNumberOfRestocks / catchUpDemand.
let missed = 2 - self.restocks_today;
if missed > 0 {
for o in &mut self.offers {
o.uses = 0;
}
}
for _ in 0..missed {
self.update_demand();
}
self.restocks_today = 0;
}
let allowed = self.restocks_today == 0
|| self.restocks_today < 2 && game_time > self.last_restock + 2400;
allowed && self.offers.iter().any(|o| o.uses > 0)
}
/// `Villager.restock`.
pub fn restock(&mut self, game_time: i64) {
self.update_demand();
for o in &mut self.offers {
o.uses = 0;
}
self.last_restock = game_time;
self.restocks_today += 1;
}
}
/// An `ItemCost`: item and count (component predicates are not used by the
@@ -582,6 +625,32 @@ mod tests {
assert_eq!(o.cost_a_count(&items), 1);
}
#[test]
fn restocks_twice_a_day() {
let mut t = Trader {
offers: vec![offer(4, None)],
..Default::default()
};
assert!(!t.should_restock(100, 0), "nothing used yet");
t.offers[0].uses = 12;
assert!(t.should_restock(100, 0));
t.restock(100);
assert_eq!(
(t.offers[0].uses, t.offers[0].demand, t.restocks_today),
(0, 12, 1)
);
t.offers[0].uses = 1;
// The second restock needs 2400 ticks since the first.
assert!(!t.should_restock(2000, 0));
assert!(t.should_restock(2600, 0));
t.restock(2600);
t.offers[0].uses = 1;
assert!(!t.should_restock(6000, 0), "two a day");
// A new day resets the count and catches up on demand.
assert!(t.should_restock(30000, 1));
assert_eq!(t.restocks_today, 0);
}
#[test]
fn payment_and_selection() {
let items = items();
+6 -1
View File
@@ -464,6 +464,9 @@ pub struct Extra {
pub vector: [f64; 3],
/// Active status effects: (effect id, ticks left, amplifier).
pub effects: Vec<(&'static str, i32, i32)>,
/// A villager's claimed bed head and meeting bell.
pub bed: Option<[i32; 3]>,
pub meeting: Option<[i32; 3]>,
/// Villager and wandering trader offers and experience.
pub trade: Option<Box<crate::merchant::Trader>>,
}
@@ -691,8 +694,9 @@ pub struct Seen {
pub variant: u8,
/// Dye colour (sheep).
pub color: u8,
/// A villager's claimed job site.
/// A villager's claimed job site and bed.
pub job: Option<[i32; 3]>,
pub bed: Option<[i32; 3]>,
}
/// The player as mobs see it.
#[derive(Clone, Debug)]
@@ -718,6 +722,7 @@ pub struct PlayerView {
}
pub struct MobWorld<'a> {
pub world: &'a World,
pub registry: &'a horizon_world::registry::BlockRegistry,
pub facts: &'a BlockFacts,
pub collision: &'a BlockCollisionRegistry<'a>,
pub data: &'a MobData,
+3 -1
View File
@@ -418,7 +418,8 @@ fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
m.ai.zza *= 0.98;
// LivingEntity.isImmobile: no goals or input (a biting, stunned or
// roaring ravager).
let immobile = m.species() == Species::Ravager && super::ravager::immobile(m);
let immobile = m.species() == Species::Ravager && super::ravager::immobile(m)
|| super::villager::sleeping(m);
if m.alive() && !immobile {
server_ai_step(m, w, events);
} else {
@@ -766,6 +767,7 @@ pub fn custom_travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec<Mo
// Shulkers never move on their own.
Family::Shulker => true,
Family::Vex => super::vex::travel(m),
Family::Villager => super::villager::travel(m),
_ => false,
}
}
+15 -2
View File
@@ -550,8 +550,21 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 {
m.previous.z + (m.position.z - m.previous.z) * a,
) - camera;
let body = m.previous_body_yaw + wrap(m.body_yaw - m.previous_body_yaw) * alpha;
let rotation = super::aquatic::rotations(m, alpha, body)
.unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians()));
let sleep = (m.species() == Species::Villager)
.then(|| super::villager::sleep_pose(m))
.flatten();
let rotation = match sleep {
// setupRotations for Pose.SLEEPING, with the head moved toward the pillow.
Some((angle, step)) => {
let head = (m.eye_y() - m.position.y) as f32 - 0.1;
glam::Mat4::from_translation(glam::Vec3::new(-step[0] * head, 0.0, -step[1] * head))
* glam::Mat4::from_rotation_y(angle.to_radians())
* glam::Mat4::from_rotation_z(90.0_f32.to_radians())
* glam::Mat4::from_rotation_y(270.0_f32.to_radians())
}
None => super::aquatic::rotations(m, alpha, body)
.unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians())),
};
let mut base = glam::Mat4::from_translation(p.as_vec3()) * rotation;
if m.death_time > 0 {
let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6)
+346 -19
View File
@@ -1,8 +1,9 @@
//! Villagers (`Villager` and its brain packages, as goals): taking the
//! profession of a free job site nearby (`AcquirePoi` with
//! `AssignProfessionFromJobSite`), losing a fresh profession when the site
//! goes (`ResetProfession`), fleeing hostiles (`VillagerPanicTrigger`) and
//! the unhappy head shake.
//! goes (`ResetProfession`), claiming a bed and a bell, the daily schedule
//! (work and restock at the job site, meet at the bell, sleep in the bed),
//! fleeing hostiles (`VillagerPanicTrigger`) and the unhappy head shake.
use super::{
Mob, MobEvent, MobWorld, Species,
anim::{Poses, State},
@@ -16,7 +17,9 @@ use std::{collections::HashMap, f32::consts::PI};
// Villager state: `variant` type, `variant2` profession (index into
// `render::PROFESSIONS`), `variant3` level, `home` the claimed job site,
// `ints[0]` the unhappy counter, `trade` the offers and experience.
// `bed` and `meeting` the claimed bed head and bell, `ints[0]` the unhappy
// counter, `ints[1]` the bed's facing while asleep (1 north, 2 south,
// 3 west, 4 east), `trade` the offers, experience and restocks.
pub const NONE: u8 = 0;
pub const NITWIT: u8 = 11;
@@ -72,6 +75,8 @@ pub fn register(m: &mut Mob) {
);
g.add(1, Panic::new(0.75));
g.add(3, JobSite::default());
g.add(3, AcquireHome::default());
g.add(4, Schedule::default());
g.add(5, Stroll::avoiding_water(0.5));
g.add(6, LookAtPlayer::new(8.0));
g.add(7, RandomLookAround::default());
@@ -93,15 +98,34 @@ fn claimed(w: &MobWorld, me: u32, p: [i32; 3]) -> bool {
fn job_seeker(m: &Mob) -> bool {
!m.is_baby() && m.extra.home.is_none() && m.extra.variant2 != NITWIT
}
/// The nearest free job site (a profession's own one once employed) within
/// 48 blocks horizontally and 8 vertically.
fn find_site(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> {
#[derive(Clone, Copy, PartialEq)]
enum Poi {
Job(u8),
Bed,
Bell,
}
fn poi_at(w: &MobWorld, state: horizon_world::registry::BlockStateId) -> Option<Poi> {
let name = &w.facts.get(state).name;
if name.as_ref() == "minecraft:bell" {
return Some(Poi::Bell);
}
if name.ends_with("_bed") {
let s = w.registry.state(state)?;
let free = s.properties.get("part").map(String::as_str) == Some("head")
&& s.properties.get("occupied").map(String::as_str) != Some("true");
return free.then_some(Poi::Bed);
}
job_site_profession(name).map(Poi::Job)
}
/// `PoiManager.findClosest` (`AcquirePoi.SCAN_RANGE` 48 blocks across, 8
/// up and down): the nearest position whose POI passes `want`.
fn scan(m: &Mob, w: &MobWorld, want: impl Fn(Poi, [i32; 3]) -> bool) -> Option<[i32; 3]> {
let (bx, by, bz) = (
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
);
let mut known: HashMap<u32, Option<u8>> = HashMap::new();
let mut known: HashMap<u32, Option<Poi>> = HashMap::new();
let mut best: Option<(i32, [i32; 3])> = None;
for y in by - 8..=by + 8 {
for z in bz - 48..=bz + 48 {
@@ -110,17 +134,10 @@ fn find_site(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> {
if w.facts.is_air(state) {
continue;
}
let profession = *known
.entry(state.0)
.or_insert_with(|| job_site_profession(&w.facts.get(state).name));
let Some(profession) = profession else {
continue;
};
if m.extra.variant2 != NONE && profession != m.extra.variant2 {
continue;
}
let poi = *known.entry(state.0).or_insert_with(|| poi_at(w, state));
let Some(poi) = poi else { continue };
let d = (x - bx).pow(2) + (y - by).pow(2) + (z - bz).pow(2);
if best.is_none_or(|(b, _)| d < b) && !claimed(w, m.id, [x, y, z]) {
if best.is_none_or(|(b, _)| d < b) && want(poi, [x, y, z]) {
best = Some((d, [x, y, z]));
}
}
@@ -128,6 +145,15 @@ fn find_site(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> {
}
best.map(|(_, p)| p)
}
/// The nearest free job site (a profession's own one once employed).
fn find_site(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> {
scan(m, w, |poi, p| match poi {
Poi::Job(profession) => {
(m.extra.variant2 == NONE || profession == m.extra.variant2) && !claimed(w, m.id, p)
}
_ => false,
})
}
impl Goal for JobSite {
goal_clone!();
fn flags(&self) -> u8 {
@@ -210,12 +236,312 @@ pub fn particles_around(m: &mut Mob, kind: &'static str, events: &mut Vec<MobEve
events.push(MobEvent::Particles { kind, at, count: 0 });
}
}
/// The `villager_activity` / `baby_villager_activity` timeline.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Activity {
Idle,
Work,
Play,
Meet,
Rest,
}
pub fn activity(m: &Mob, day_time: i64) -> Activity {
let t = day_time.rem_euclid(24000);
if m.is_baby() {
match t {
10..3000 | 6000..10000 => Activity::Idle,
3000..6000 | 10000..12000 => Activity::Play,
_ => Activity::Rest,
}
} else {
match t {
10..2000 | 11000..12000 => Activity::Idle,
2000..9000 => Activity::Work,
9000..11000 => Activity::Meet,
_ => Activity::Rest,
}
}
}
fn center(p: [i32; 3]) -> [f64; 3] {
[
f64::from(p[0]) + 0.5,
f64::from(p[1]) + 0.5,
f64::from(p[2]) + 0.5,
]
}
fn distance(m: &Mob, p: [i32; 3]) -> f64 {
let c = center(p);
m.position
.distance_squared(horizon_core::geometry::Vec3::new(c[0], c[1], c[2]))
.sqrt()
}
/// `AcquirePoi` for `HOME` (a free bed head) and `MEETING` (a bell), with
/// the happy particles on success; failed scans back off.
#[derive(Clone, Debug, Default)]
struct AcquireHome {
next_search: i32,
}
impl Goal for AcquireHome {
goal_clone!();
fn flags(&self) -> u8 {
0
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if m.extra.bed.is_some() && m.extra.meeting.is_some() {
return false;
}
if self.next_search > 0 {
self.next_search -= 1;
return false;
}
let w = cx.w;
let mut found = false;
if m.extra.bed.is_none()
&& let Some(p) = scan(m, w, |poi, p| {
poi == Poi::Bed
&& !w
.others
.iter()
.any(|s| s.id != m.id && s.alive && s.bed == Some(p))
})
{
m.extra.bed = Some(p);
found = true;
}
if m.extra.meeting.is_none()
&& !m.is_baby()
&& let Some(p) = scan(m, w, |poi, _| poi == Poi::Bell)
{
m.extra.meeting = Some(p);
found = true;
}
if found {
particles_around(m, "happy_villager", cx.events);
}
self.next_search = if found {
20 + m.random.next_int_bound(20).unwrap_or(0)
} else {
200 + m.random.next_int_bound(200).unwrap_or(0)
};
false
}
}
/// The schedule's walk targets (`SetWalkTargetFromBlockMemory`,
/// `StrollToPoi`, `StrollAroundPoi`), `WorkAtPoi` with restocking, and
/// `SleepInBed`.
#[derive(Clone, Debug, Default)]
struct Schedule {
cooldown: i32,
target: Option<[f64; 3]>,
to_site: bool,
last_work: i64,
ticks: i32,
}
impl Schedule {
fn anchor(m: &Mob, a: Activity) -> Option<([i32; 3], f64)> {
match a {
Activity::Work if m.extra.variant2 != NONE && m.extra.variant2 != NITWIT => {
m.extra.home.map(|p| (p, 9.0))
}
Activity::Meet => m.extra.meeting.map(|p| (p, 6.0)),
Activity::Rest => m.extra.bed.map(|p| (p, 1.0)),
_ => None,
}
}
}
impl Goal for Schedule {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if sleeping(m) {
return false;
}
if self.cooldown > 0 {
self.cooldown -= 1;
return false;
}
let a = activity(m, cx.w.day_time);
let Some((p, close)) = Self::anchor(m, a) else {
return false;
};
self.to_site = false;
let c = center(p);
self.target = if a == Activity::Rest || distance(m, p) > close {
self.to_site = true;
Some(c)
} else if m.random.next_int_bound(2).unwrap_or(0) == 0 && a == Activity::Work {
// StrollToPoi / WorkAtPoi.
self.to_site = true;
Some(c)
} else {
// StrollAroundPoi: somewhere near the site.
let r = &mut m.random;
let spread = if a == Activity::Meet { 6 } else { 4 };
let mut d = || f64::from(r.next_int_bound(2 * spread + 1).unwrap_or(0) - spread);
Some([c[0] + d(), c[1], c[2] + d()])
};
self.cooldown = 40 + m.random.next_int_bound(80).unwrap_or(0);
true
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.ticks < 400
&& !sleeping(m)
&& Self::anchor(m, activity(m, cx.w.day_time)).is_some()
&& !(m.ai.nav.is_done() && self.ticks > 20)
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
self.ticks = 0;
if let Some(t) = self.target {
m.nav_move_to(cx.w, t, 0.5);
}
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
m.nav_stop();
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
self.ticks += 1;
let a = activity(m, cx.w.day_time);
let Some((p, _)) = Self::anchor(m, a) else {
return;
};
if !self.to_site {
return;
}
match a {
Activity::Work if distance(m, p) < 1.73 => {
// WorkAtPoi: every 300 ticks at most, half the time.
let now = cx.w.game_time;
m.look_at(center(p));
if now - self.last_work >= 300 && m.random.next_int_bound(2).unwrap_or(1) == 0 {
self.last_work = now;
work(m, cx.w, cx.events);
}
m.nav_stop();
}
Activity::Rest if distance(m, p) < 2.0 => start_sleeping(m, p, cx.w),
_ => {}
}
}
}
/// `WorkAtPoi.start`: the profession's work sound, and a restock when due.
fn work(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
let profession = super::render::PROFESSIONS[m.extra.variant2 as usize % 15];
events.push(MobEvent::SoundId(
format!("minecraft:entity.villager.work_{profession}"),
[m.position.x, m.position.y, m.position.z],
1.0,
1.0,
));
let day = w.day_time.div_euclid(24000);
if let Some(t) = m.extra.trade.as_mut()
&& t.should_restock(w.game_time, day)
{
t.restock(w.game_time);
}
}
pub fn sleeping(m: &Mob) -> bool {
m.extra.ints[1] != 0
}
/// `LivingEntity.startSleeping`: lie in the bed (`setPosToBed`).
fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) {
if w.prop(p[0], p[1], p[2], "occupied") == Some("true") {
return;
}
m.extra.ints[1] = match w.prop(p[0], p[1], p[2], "facing") {
Some("north") => 1,
Some("south") => 2,
Some("west") => 3,
_ => 4,
};
m.nav_stop();
m.velocity = horizon_core::geometry::Vec3::ZERO;
m.position = horizon_core::geometry::Vec3::new(
f64::from(p[0]) + 0.5,
f64::from(p[1]) + 0.6875,
f64::from(p[2]) + 0.5,
);
}
/// `LivingEntity.stopSleeping` with `BedBlock.findStandUpPosition`: beside
/// the bed where there is room, else on top of it.
pub fn stop_sleeping(m: &mut Mob, w: &MobWorld) {
m.extra.ints[1] = 0;
let Some(p) = m.extra.bed else { return };
for (dx, dz) in [
(1, 0),
(-1, 0),
(0, 1),
(0, -1),
(1, 1),
(-1, -1),
(1, -1),
(-1, 1),
] {
let (x, y, z) = (p[0] + dx, p[1], p[2] + dz);
let free = |y| w.data.state(w.world.block(x, y, z)).top <= 0.0;
if free(y) && free(y + 1) && w.solid(x, y - 1, z) {
m.position = horizon_core::geometry::Vec3::new(
f64::from(x) + 0.5,
f64::from(y),
f64::from(z) + 0.5,
);
return;
}
}
m.position.y = f64::from(p[1]) + 0.5625;
}
/// While asleep the villager stays in the bed.
pub fn travel(m: &mut Mob) -> bool {
if !sleeping(m) {
return false;
}
m.velocity = horizon_core::geometry::Vec3::ZERO;
true
}
/// `LivingEntityRenderer.sleepDirectionToRotation` and the bed's direction
/// (the body is shifted back from the pillow by the standing eye height).
pub fn sleep_pose(m: &Mob) -> Option<(f32, [f32; 2])> {
Some(match m.extra.ints[1] {
1 => (270.0, [0.0, -1.0]),
2 => (90.0, [0.0, 1.0]),
3 => (0.0, [-1.0, 0.0]),
4 => (180.0, [1.0, 0.0]),
_ => return None,
})
}
/// `Villager.tick` / brain upkeep: the unhappy counter, and
/// `ResetProfession` / job site loss when the site's block is gone.
pub fn ai_step(m: &mut Mob, w: &MobWorld) {
if m.extra.ints[0] > 0 {
m.extra.ints[0] -= 1;
}
// WakeUp / LivingEntity.hurt: morning, a hit or a missing bed.
if sleeping(m) {
let bed_gone = m
.extra
.bed
.is_none_or(|p| !w.block_name(p[0], p[1], p[2]).ends_with("_bed"));
if activity(m, w.day_time) != Activity::Rest || m.hurt_time > 0 || bed_gone {
stop_sleeping(m, w);
}
}
// ValidateNearbyPoi for the bed and bell.
if m.age.is_multiple_of(20) {
let loaded = |p: [i32; 3]| w.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4));
if let Some(p) = m.extra.bed
&& loaded(p)
&& !w.block_name(p[0], p[1], p[2]).ends_with("_bed")
{
m.extra.bed = None;
}
if let Some(p) = m.extra.meeting
&& loaded(p)
&& w.block_name(p[0], p[1], p[2]) != "minecraft:bell"
{
m.extra.meeting = None;
}
}
if m.species() != Species::Villager || !m.age.is_multiple_of(20) {
return;
}
@@ -250,8 +576,9 @@ pub fn set_unhappy(m: &mut Mob, events: &mut Vec<MobEvent>) {
}
/// `VillagerModel.setupAnim`.
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot("head", s.y_rot.to_radians());
p.xrot("head", s.x_rot.to_radians());
let awake = !sleeping(m);
p.yrot("head", if awake { s.y_rot.to_radians() } else { 0.0 });
p.xrot("head", if awake { s.x_rot.to_radians() } else { 0.0 });
if m.extra.ints[0] > 0 {
p.zrot("head", 0.3 * (0.45 * s.age).sin());
p.xrot("head", 0.4);
+7
View File
@@ -47,6 +47,13 @@ impl MobWorld<'_> {
pub fn block_name(&self, x: i32, y: i32, z: i32) -> &str {
&self.facts.get(self.world.block(x, y, z)).name
}
/// A block state property's value.
pub fn prop(&self, x: i32, y: i32, z: i32, key: &str) -> Option<&str> {
self.registry
.state(self.world.block(x, y, z))
.and_then(|s| s.properties.get(key))
.map(String::as_str)
}
pub fn has_tag(&self, tag: &str, block: &str) -> bool {
self.block_tags.get(tag).is_some_and(|s| s.contains(block))
}