Let villagers take jobs and trade

Villagers claim the nearest free job site within 48 blocks and take its
profession, lose a fresh profession when the site goes, flee zombies and
raiders, and shake their heads when they have nothing to sell.
Right-clicking a villager or wandering trader opens its trades; offers,
experience, level, profession and job site are saved as vanilla NBT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-09 11:04:32 +02:00
parent 07e36a90d3
commit 2b664b4c4e
10 changed files with 568 additions and 14 deletions
+131
View File
@@ -246,6 +246,32 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
}
map.insert("equipment".into(), Tag::Compound(equipment));
}
"minecraft:villager" => {
use crate::mobs::render::{PROFESSIONS, VILLAGER_TYPES};
let data = Tag::compound([
(
"type",
string(&format!(
"minecraft:{}",
VILLAGER_TYPES[m.extra.variant as usize % VILLAGER_TYPES.len()]
)),
),
(
"profession",
string(&format!(
"minecraft:{}",
PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()]
)),
),
("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));
put_offers(map, m);
put_job_site(map, m.extra.home);
}
"minecraft:wandering_trader" => put_offers(map, m),
"minecraft:allay" => {
// InventoryCarrier: the fetched stack; the liked player memory.
let mut inv = Vec::new();
@@ -497,6 +523,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
.unwrap_or(0) as u8;
}
}
if matches!(
m.species(),
crate::mobs::Species::Villager | crate::mobs::Species::WanderingTrader
) {
read_villager(&mut m, tag);
}
if m.species() == crate::mobs::Species::Allay {
if let Some(Tag::List(inv)) = tag.get("Inventory")
&& let Some(first) = inv.first()
@@ -938,6 +970,105 @@ pub fn boat_from_nbt(tag: &Tag) -> Option<(Vec3, Vec3, f32)> {
Some((position(tag)?, motion(tag), rotation(tag)[0]))
}
/// `AbstractVillager` "Offers" (`MerchantOffers.CODEC`).
fn put_offers(map: &mut Compound, m: &Mob) {
let Some(t) = &m.extra.trade else { return };
let recipes = t
.offers
.iter()
.map(|o| {
let mut entries = vec![
("buy", item_to_nbt(&o.base_cost_a.stack)),
("sell", item_to_nbt(&o.result)),
("uses", Tag::Int(o.uses)),
("maxUses", Tag::Int(o.max_uses)),
("rewardExp", Tag::Byte(i8::from(o.reward_exp))),
("specialPrice", Tag::Int(o.special_price_diff)),
("demand", Tag::Int(o.demand)),
("priceMultiplier", Tag::Float(o.price_multiplier.to_bits())),
("xp", Tag::Int(o.xp)),
];
if let Some(b) = &o.cost_b {
entries.push(("buyB", item_to_nbt(&b.stack)));
}
Tag::compound(entries)
})
.collect();
map.insert(
"Offers".into(),
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())),
]);
map.insert(
"Brain".into(),
Tag::compound([(
"memories",
Tag::compound([("minecraft:job_site", Tag::compound([("value", pos)]))]),
)]),
);
}
fn read_villager(m: &mut Mob, tag: &Tag) {
use crate::{
merchant::{ItemCost, MerchantOffer, Trader},
mobs::render::{PROFESSIONS, VILLAGER_TYPES},
};
if let Some(data) = tag.get("VillagerData") {
let name = |key| text(data.get(key)).map(|s| s.trim_start_matches("minecraft:").to_owned());
if let Some(t) = name("type").and_then(|t| VILLAGER_TYPES.iter().position(|v| *v == t)) {
m.extra.variant = t as u8;
}
m.extra.variant2 = name("profession")
.and_then(|p| PROFESSIONS.iter().position(|v| *v == p))
.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 Some(Tag::List(recipes)) = tag.get("Offers").and_then(|o| o.get("Recipes")) else {
return;
};
let offers = recipes
.iter()
.filter_map(|r| {
let cost = |key| {
r.get(key)
.and_then(item_from_nbt)
.map(|stack| ItemCost { stack })
};
Some(MerchantOffer {
base_cost_a: cost("buy")?,
cost_b: cost("buyB"),
result: r.get("sell").and_then(item_from_nbt)?,
uses: number(r.get("uses")).unwrap_or(0) as i32,
max_uses: number(r.get("maxUses")).unwrap_or(4) as i32,
reward_exp: number(r.get("rewardExp")).unwrap_or(1) != 0,
special_price_diff: number(r.get("specialPrice")).unwrap_or(0) as i32,
demand: number(r.get("demand")).unwrap_or(0) as i32,
price_multiplier: float(r.get("priceMultiplier")).unwrap_or(0.0) as f32,
xp: number(r.get("xp")).unwrap_or(1) as i32,
})
})
.collect();
m.extra.trade = Some(Box::new(Trader {
xp: number(tag.get("Xp")).unwrap_or(0) as i32,
offers,
}));
}
#[cfg(test)]
mod tests {
use super::*;
@@ -109,6 +109,9 @@ fn seen(m: &Mob) -> Seen {
health: m.health,
variant: m.extra.variant,
color: m.extra.color,
job: (m.species() == Species::Villager)
.then_some(m.extra.home)
.flatten(),
}
}
impl Game<'_> {
@@ -1598,6 +1601,10 @@ impl Game<'_> {
.unwrap_or_default();
let creative = self.creative;
let selected = self.selected;
if self.interact_trader(index, &item)? {
self.swing_arm();
return Ok(true);
}
if self.interact_allay(index, &item) {
self.swing_arm();
return Ok(true);
@@ -299,6 +299,9 @@ impl Game<'_> {
let Some(station) = self.station.take() else {
return;
};
if let Some(m) = &station.merchant {
self.merchant_closed(m);
}
for stack in station.inputs.into_iter().flatten() {
self.give_or_drop(stack);
}
+139 -13
View File
@@ -6,6 +6,11 @@ use super::{
Game,
stations::{INPUT, Kind, RESULT, Station},
};
use horizon_client::mobs::{
Species,
render::{PROFESSIONS, VILLAGER_TYPES},
villager,
};
use horizon_client::{
hud::{HudBatch, rgba},
items::ItemStack,
@@ -30,6 +35,16 @@ pub(super) struct MerchantState {
pub(super) future_xp: i32,
/// The offer button that keeps focus after a click (drawn highlighted).
pub(super) focused: Option<usize>,
/// The trading mob (its offers and experience are written back on
/// close) and its custom name.
pub(super) mob: Option<u32>,
pub(super) name: Option<String>,
}
impl MerchantState {
/// `Merchant.showProgressBar`: villagers only.
pub(super) fn progress(&self) -> bool {
self.profession != "wandering_trader"
}
}
/// Player inventory slot positions in `MerchantMenu` (x from 108).
pub(super) fn inventory_slot(i: usize) -> (f32, f32) {
@@ -64,6 +79,10 @@ impl Game<'_> {
/// Offers a villager of `profession` gets on reaching `level`.
fn new_offers(&mut self, profession: &str, variant: &str, level: i32) -> Vec<MerchantOffer> {
let set = merchant::Trades::set_for(profession, level);
self.offers_from_set(&set, variant)
}
/// `AbstractVillager.addOffersFromTradeSet`.
fn offers_from_set(&mut self, set: &str, variant: &str) -> Vec<MerchantOffer> {
let sequence = format!(
"minecraft:trade_set/{}",
set.trim_start_matches("minecraft:")
@@ -78,7 +97,97 @@ impl Game<'_> {
enchantments: &self.res.stations.enchantments,
variant,
};
self.res.stations.trades.offers_from_set(&ctx, &set, random)
self.res.stations.trades.offers_from_set(&ctx, set, random)
}
/// `Villager.mobInteract` / `WanderingTrader.mobInteract`: shake the
/// head without offers, else open the trading screen.
pub(super) fn interact_trader(
&mut self,
index: usize,
item: &str,
) -> horizon_client::Result<bool> {
let m = &self.mobs[index];
let species = m.species();
if !matches!(species, Species::Villager | Species::WanderingTrader)
|| !m.alive()
|| item == "minecraft:villager_spawn_egg"
|| self.station.is_some()
{
return Ok(false);
}
if m.is_baby() {
let mut events = Vec::new();
villager::set_unhappy(&mut self.mobs[index], &mut events);
self.handle_mob_events(events)?;
return Ok(true);
}
// AbstractVillager.getOffers: generated on first use.
if self.mobs[index].extra.trade.is_none() {
let m = &self.mobs[index];
let variant = VILLAGER_TYPES[m.extra.variant as usize % VILLAGER_TYPES.len()];
let offers = if species == Species::WanderingTrader {
let mut v = Vec::new();
for set in ["buying", "uncommon", "common"] {
v.extend(
self.offers_from_set(&format!("minecraft:wandering_trader/{set}"), variant),
);
}
v
} else {
let profession = PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()];
let level = i32::from(m.extra.variant3.max(1));
if matches!(profession, "none" | "nitwit") {
Vec::new()
} else {
self.new_offers(profession, variant, level)
}
};
self.mobs[index].extra.trade = Some(Box::new(merchant::Trader { xp: 0, offers }));
}
let m = &self.mobs[index];
let trade = m.extra.trade.as_deref().cloned().unwrap_or_default();
if trade.offers.is_empty() {
let mut events = Vec::new();
villager::set_unhappy(&mut self.mobs[index], &mut events);
self.handle_mob_events(events)?;
return Ok(true);
}
let profession = if species == Species::WanderingTrader {
"wandering_trader"
} else {
PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()]
};
let state = MerchantState {
profession: profession.to_owned(),
variant: VILLAGER_TYPES[m.extra.variant as usize % VILLAGER_TYPES.len()].to_owned(),
level: i32::from(m.extra.variant3.max(1)).min(5),
xp: trade.xp,
offers: trade.offers,
shop_item: 0,
scroll: 0,
active: None,
future_xp: 0,
focused: None,
mob: Some(m.id),
name: m.custom_name.clone(),
};
self.open_merchant_state(state);
Ok(true)
}
/// `Villager.setTradingPlayer(null)`: the menu's offers and experience
/// go back to the mob.
pub(super) fn merchant_closed(&mut self, state: &MerchantState) {
let Some(id) = state.mob else { return };
let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else {
return;
};
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(),
}));
}
/// 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) {
@@ -86,8 +195,7 @@ impl Game<'_> {
for l in 1..=level.clamp(1, 5) {
offers.extend(self.new_offers(profession, variant, l));
}
let mut s = Station::new_kind(Kind::Merchant, [0, 0, 0]);
s.merchant = Some(Box::new(MerchantState {
self.open_merchant_state(MerchantState {
profession: profession.trim_start_matches("minecraft:").to_owned(),
variant: variant.to_owned(),
level: level.clamp(1, 5),
@@ -98,7 +206,13 @@ impl Game<'_> {
active: None,
future_xp: 0,
focused: None,
}));
mob: None,
name: None,
});
}
fn open_merchant_state(&mut self, state: MerchantState) {
let mut s = Station::new_kind(Kind::Merchant, [0, 0, 0]);
s.merchant = Some(Box::new(state));
self.station = Some(s);
self.screen = super::Screen::Inventory;
self.capture(false);
@@ -120,7 +234,8 @@ impl Game<'_> {
m.offers[i].uses += 1;
let mut pop = 3 + self.world.random.next_int_bound(4).unwrap_or(0);
m.xp += offer.xp;
let level_up = merchant::can_level_up(m.level) && m.xp >= merchant::max_xp(m.level);
let level_up =
m.progress() && merchant::can_level_up(m.level) && m.xp >= merchant::max_xp(m.level);
let at = self
.player
.as_ref()
@@ -246,6 +361,7 @@ impl Game<'_> {
let Some(m) = self.station.as_ref().and_then(|s| s.merchant.as_ref()) else {
return false;
};
let (progress, custom) = (m.progress(), m.name.clone());
let (profession, level, xp, scroll, shop, future, focused) = (
m.profession.clone(),
m.level,
@@ -274,13 +390,23 @@ impl Game<'_> {
}
let e = &self.res.stations.enchantments;
let tr = |k: &str, f: &str| e.translate(k).unwrap_or(f).to_owned();
let name = tr(
&format!("entity.minecraft.villager.{profession}"),
&profession,
);
let title = tr("merchant.title", "%s - %s")
.replacen("%s", &name, 1)
.replacen("%s", &tr(&format!("merchant.level.{level}"), ""), 1);
let name = custom.unwrap_or_else(|| {
if progress {
tr(
&format!("entity.minecraft.villager.{profession}"),
&profession,
)
} else {
tr("entity.minecraft.wandering_trader", "Wandering Trader")
}
});
let title = if progress {
tr("merchant.title", "%s - %s")
.replacen("%s", &name, 1)
.replacen("%s", &tr(&format!("merchant.level.{level}"), ""), 1)
} else {
name
};
let tw = HudBatch::text_width(atlas, &title);
batch.text(
atlas,
@@ -317,7 +443,7 @@ impl Game<'_> {
);
}
// Experience bar (levels 1-4).
if level < 5 {
if progress && level < 5 {
batch.sprite(
atlas,
"gui/sprites/container/villager/experience_bar_background",
+8
View File
@@ -47,6 +47,14 @@ pub const PROFESSIONS: &[&str] = &[
"weaponsmith",
];
/// A villager's or wandering trader's trading state (`AbstractVillager.offers`
/// and `Villager.villagerXp`); `None` on the mob until its offers are first asked for.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Trader {
pub xp: i32,
pub offers: Vec<MerchantOffer>,
}
/// An `ItemCost`: item and count (component predicates are not used by the
/// 26.3 trade data except for one exact match, kept as the stack's data).
#[derive(Clone, Debug, PartialEq)]
+5
View File
@@ -36,6 +36,7 @@ pub mod species;
pub mod tame;
pub mod undead;
pub mod vex;
pub mod villager;
pub mod witch;
pub mod wither;
mod world;
@@ -463,6 +464,8 @@ pub struct Extra {
pub vector: [f64; 3],
/// Active status effects: (effect id, ticks left, amplifier).
pub effects: Vec<(&'static str, i32, i32)>,
/// Villager and wandering trader offers and experience.
pub trade: Option<Box<crate::merchant::Trader>>,
}
#[derive(Clone, Debug)]
pub struct Mob {
@@ -688,6 +691,8 @@ pub struct Seen {
pub variant: u8,
/// Dye colour (sheep).
pub color: u8,
/// A villager's claimed job site.
pub job: Option<[i32; 3]>,
}
/// The player as mobs see it.
#[derive(Clone, Debug)]
+4
View File
@@ -86,6 +86,7 @@ pub enum Family {
Ravager,
Wither,
Allay,
Villager,
}
pub fn family(s: Species) -> Family {
use Species as S;
@@ -120,6 +121,7 @@ pub fn family(s: Species) -> Family {
S::Ravager => Family::Ravager,
S::Wither => Family::Wither,
S::Allay => Family::Allay,
S::Villager => Family::Villager,
S::Piglin | S::PiglinBrute | S::Hoglin | S::Zoglin => Family::Piglin,
S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse | S::Camel => {
Family::Equine
@@ -166,6 +168,7 @@ pub fn register(m: &mut Mob) {
Family::Ravager => super::ravager::register(m),
Family::Wither => super::wither::register(m),
Family::Allay => super::allay::register(m),
Family::Villager => super::villager::register(m),
}
}
/// Mob.tick additions that run before the entity tick (creeper fuse, puffing).
@@ -560,6 +563,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
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::Villager | Species::WanderingTrader => super::villager::ai_step(m, w),
Species::Shulker => {
super::shulker::tick(m, w, events);
super::shulker::ai_step(m, w, events);
+1
View File
@@ -456,6 +456,7 @@ pub fn setup(
}
}
Anim::Witch => super::witch::anim(m, s, p),
Anim::Villager => super::villager::anim(m, s, p),
Anim::Wolf => super::tame::anim(m, s, p),
Anim::IronGolem => super::golem::iron_anim(m, s, p),
Anim::Illager => super::illager::anim(m, s, p),
+1 -1
View File
@@ -57,7 +57,7 @@ pub fn sheep_wool_rgb(color: u8) -> u32 {
let f = |c: u32| ((c as f32 * 0.75).floor() as u32).min(255);
f(src >> 16 & 255) << 16 | f(src >> 8 & 255) << 8 | f(src & 255)
}
const VILLAGER_TYPES: [&str; 7] = [
pub const VILLAGER_TYPES: [&str; 7] = [
"plains", "desert", "jungle", "savanna", "snow", "swamp", "taiga",
];
pub const PROFESSIONS: [&str; 15] = [
+269
View File
@@ -0,0 +1,269 @@
//! 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.
use super::{
Mob, MobEvent, MobWorld, Species,
anim::{Poses, State},
goals::{
Avoid, AvoidEntity, Cx, Float, Goal, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll,
goal_clone,
},
};
use horizon_core::random::RandomSource;
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.
pub const NONE: u8 = 0;
pub const NITWIT: u8 = 11;
/// `PoiTypes`: the job site block of each profession.
pub fn job_site_profession(block: &str) -> Option<u8> {
Some(match block.trim_start_matches("minecraft:") {
"blast_furnace" => 1,
"smoker" => 2,
"cartography_table" => 3,
"brewing_stand" => 4,
"composter" => 5,
"barrel" => 6,
"fletching_table" => 7,
"cauldron" | "water_cauldron" | "lava_cauldron" | "powder_snow_cauldron" => 8,
"lectern" => 9,
"stonecutter" => 10,
"loom" => 12,
"smithing_table" => 13,
"grindstone" => 14,
_ => return None,
})
}
pub fn register(m: &mut Mob) {
if m.extra.variant3 == 0 {
m.extra.variant3 = 1;
}
let g = &mut m.ai.goals;
g.add(0, Float);
// VillagerHostilesSensor: zombies within 8 blocks, illagers further.
let zombies = vec![
Species::Zombie,
Species::ZombieVillager,
Species::Husk,
Species::Drowned,
Species::Vex,
];
let raiders = vec![
Species::Pillager,
Species::Vindicator,
Species::Evoker,
Species::Ravager,
Species::Zoglin,
];
g.add(
1,
AvoidEntity::new(Avoid::Species(zombies), 8.0, 0.75, 0.75),
);
g.add(
1,
AvoidEntity::new(Avoid::Species(raiders), 12.0, 0.75, 0.75),
);
g.add(1, Panic::new(0.75));
g.add(3, JobSite::default());
g.add(5, Stroll::avoiding_water(0.5));
g.add(6, LookAtPlayer::new(8.0));
g.add(7, RandomLookAround::default());
}
/// `AcquirePoi` for job sites with `AssignProfessionFromJobSite`: walk to the
/// nearest unclaimed job site and take its profession once within 2 blocks.
#[derive(Clone, Debug, Default)]
struct JobSite {
target: Option<[i32; 3]>,
next_search: i32,
ticks: i32,
}
fn claimed(w: &MobWorld, me: u32, p: [i32; 3]) -> bool {
w.others
.iter()
.any(|s| s.id != me && s.alive && s.job == Some(p))
}
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]> {
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 best: Option<(i32, [i32; 3])> = None;
for y in by - 8..=by + 8 {
for z in bz - 48..=bz + 48 {
for x in bx - 48..=bx + 48 {
let state = w.world.block(x, y, z);
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 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]) {
best = Some((d, [x, y, z]));
}
}
}
}
best.map(|(_, p)| p)
}
impl Goal for JobSite {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !job_seeker(m) {
return false;
}
if self.next_search > 0 {
self.next_search -= 1;
return false;
}
// AcquirePoi's scan pacing: 20 to 40 ticks between scans.
self.next_search = 20 + m.random.next_int_bound(20).unwrap_or(0);
self.target = find_site(m, cx.w);
self.target.is_some()
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
job_seeker(m)
&& self.ticks < 1200
&& self.target.is_some_and(|p| {
job_site_profession(cx.w.block_name(p[0], p[1], p[2])).is_some()
&& !claimed(cx.w, m.id, p)
})
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
self.ticks = 0;
if let Some(p) = self.target {
let path = m.create_path_to(cx.w, p, 1);
m.nav_move_to_path(path, 0.5);
}
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
m.nav_stop();
self.target = None;
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
self.ticks += 1;
let Some(p) = self.target else { return };
let c = [
f64::from(p[0]) + 0.5,
f64::from(p[1]) + 0.5,
f64::from(p[2]) + 0.5,
];
if m.position
.distance_squared(horizon_core::geometry::Vec3::new(c[0], c[1], c[2]))
< 4.0
{
take_job(m, p, cx.w, cx.events);
return;
}
if m.ai.nav.is_done() && self.ticks % 40 == 0 {
let path = m.create_path_to(cx.w, p, 1);
m.nav_move_to_path(path, 0.5);
}
}
}
/// `AssignProfessionFromJobSite`: claim the site, take its profession if
/// unemployed, and show the happy particles (entity event 14).
fn take_job(m: &mut Mob, p: [i32; 3], w: &MobWorld, events: &mut Vec<MobEvent>) {
m.extra.home = Some(p);
if m.extra.variant2 == NONE
&& let Some(profession) = job_site_profession(w.block_name(p[0], p[1], p[2]))
{
m.extra.variant2 = profession;
m.extra.trade = None;
}
particles_around(m, "happy_villager", events);
}
/// `LivingEntity.addParticlesAroundSelf`: five particles about the body.
pub fn particles_around(m: &mut Mob, kind: &'static str, events: &mut Vec<MobEvent>) {
let (w, h) = (f64::from(m.width()), f64::from(m.height()));
for _ in 0..5 {
let at = [
m.position.x + w * (2.0 * m.random.next_double() - 1.0),
m.position.y + h * m.random.next_double() + 1.0,
m.position.z + w * (2.0 * m.random.next_double() - 1.0),
];
events.push(MobEvent::Particles { kind, at, count: 0 });
}
}
/// `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;
}
if m.species() != Species::Villager || !m.age.is_multiple_of(20) {
return;
}
let Some(p) = m.extra.home else { return };
if !w.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) {
return;
}
if job_site_profession(w.block_name(p[0], p[1], p[2])).is_none() {
m.extra.home = None;
let fresh = m.extra.trade.as_ref().is_none_or(|t| t.xp == 0);
if m.extra.variant2 != NONE && m.extra.variant2 != NITWIT && fresh && m.extra.variant3 <= 1
{
m.extra.variant2 = NONE;
m.extra.trade = None;
}
}
}
/// `Villager.setUnhappy`: shake the head for two seconds and say no.
pub fn set_unhappy(m: &mut Mob, events: &mut Vec<MobEvent>) {
m.extra.ints[0] = 40;
let sound = if m.species() == Species::WanderingTrader {
"entity.wandering_trader.no"
} else {
"entity.villager.no"
};
events.push(MobEvent::Sound(
sound,
[m.position.x, m.position.y, m.position.z],
1.0,
1.0,
));
}
/// `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());
if m.extra.ints[0] > 0 {
p.zrot("head", 0.3 * (0.45 * s.age).sin());
p.xrot("head", 0.4);
} else {
p.zrot("head", 0.0);
}
let leg = (s.pos * 0.6662).cos() * 1.4 * s.speed * 0.5;
p.xrot("right_leg", leg);
p.xrot(
"left_leg",
(s.pos * 0.6662 + PI).cos() * 1.4 * s.speed * 0.5,
);
p.yrot("right_leg", 0.0);
p.yrot("left_leg", 0.0);
}