Add villager gossip, breeding and golem defence

Villagers remember players through gossip (major and minor, positive and
negative, and trading) that fades by the day and spreads when villagers
meet, saved with each villager. Hitting a villager earns a minor negative
mark, killing one in front of others a major one, and each trade a small
positive one; the reputation changes the prices, as does Hero of the
Village. Villagers that meet swap gossip, pass surplus food to hungry
neighbours (farmers to anyone) and wares to the profession that wants them,
pick up food and seeds from the ground into an eight-slot inventory, and
willing pairs (twelve food points, awake, adult) make a baby after about
fourteen seconds when a free bed is within 48 blocks. Frightened villagers
and gossiping groups that slept lately call for an iron golem, and golems
defend a village against a player whom a villager nearby holds at minus
100. Bottles from structure loot keep their amplifier.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-09 13:16:57 +02:00
parent 44adeb0d3c
commit 7bbc85efa0
13 changed files with 1613 additions and 11 deletions
+6 -1
View File
@@ -280,6 +280,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
map.insert("RestocksToday".into(), Tag::Int(t.restocks_today));
put_offers(map, m);
put_memories(map, m);
crate::mobs::villager::write_nbt(m, map);
}
"minecraft:wandering_trader" => put_offers(map, m),
"minecraft:allay" => {
@@ -1046,7 +1047,7 @@ fn put_offers(map: &mut Compound, m: &Mob) {
}
/// The villager brain's `job_site`, `home` and `meeting_point` memories.
fn put_memories(map: &mut Compound, m: &Mob) {
let memories: Vec<(&str, Tag)> = [
let mut memories: Vec<(&str, Tag)> = [
("minecraft:job_site", m.extra.home),
("minecraft:home", m.extra.bed),
("minecraft:meeting_point", m.extra.meeting),
@@ -1060,6 +1061,7 @@ fn put_memories(map: &mut Compound, m: &Mob) {
Some((key, Tag::compound([("value", pos)])))
})
.collect();
crate::mobs::villager::write_memories(m, &mut memories);
map.insert(
"Brain".into(),
Tag::compound([("memories", Tag::compound(memories))]),
@@ -1093,6 +1095,9 @@ fn read_villager(m: &mut Mob, tag: &Tag) {
m.extra.home = memory("minecraft:job_site");
m.extra.bed = memory("minecraft:home");
m.extra.meeting = memory("minecraft:meeting_point");
if m.species() == crate::mobs::Species::Villager {
crate::mobs::villager::read_nbt(m, tag);
}
let Some(Tag::List(recipes)) = tag.get("Offers").and_then(|o| o.get("Recipes")) else {
return;
};
+1
View File
@@ -63,6 +63,7 @@ mod tnt;
mod totem;
mod trading;
mod trident;
mod villagers;
mod wither;
use horizon_client::{
Result,
+38 -3
View File
@@ -93,7 +93,8 @@ impl ProjectileWorld for ProjWorld<'_, '_> {
.full_collision
}
}
fn seen(m: &Mob) -> Seen {
fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen {
let villager = m.species() == Species::Villager;
Seen {
id: m.id,
species: m.species(),
@@ -102,7 +103,12 @@ fn seen(m: &Mob) -> Seen {
eye_y: m.eye_y(),
alive: m.alive(),
baby: m.is_baby(),
in_love: m.extra.in_love > 0,
// A villager is "in love" when it is willing to breed (`canBreed`).
in_love: if villager {
horizon_client::mobs::villager::can_breed(m)
} else {
m.extra.in_love > 0
},
tame: m.extra.tame,
hostile: m.hostile(),
target: m.ai.target,
@@ -116,6 +122,12 @@ fn seen(m: &Mob) -> Seen {
.then_some(m.extra.bed)
.flatten(),
active_raid: horizon_client::mobs::raider::has_active_raid(m),
player_rep: match (villager, player) {
(true, Some(uuid)) => {
horizon_client::mobs::villager::ext(m).map_or(0, |e| e.gossips.reputation(uuid))
}
_ => 0,
},
}
}
impl Game<'_> {
@@ -152,6 +164,7 @@ impl Game<'_> {
hurt_by: self.player_hurt_by(),
last_hurt: self.combat.last_hurt_mob.map(|(id, at)| (Who::Mob(id), at)),
hero: self.potions.effects.get("hero_of_the_village").is_some(),
uuid: self.level.player_uuid.unwrap_or_default(),
})
}
/// Biome facts at a position for finalizeSpawn and variant rules.
@@ -280,6 +293,21 @@ impl Game<'_> {
"on_ground": m.on_ground,
"variant": m.extra.variant,
"color": m.extra.color,
"villager": horizon_client::mobs::villager::ext(m).map(|e| serde_json::json!({
"food_level": e.food_level,
"inventory": e.inventory.iter().map(|s| format!("{}x{}", s.count, s.item)).collect::<Vec<_>>(),
"gossips": e.gossips.len(),
"last_slept": e.last_slept,
"raid": e.raid,
})),
"raider": horizon_client::mobs::raider::state(m).map(|s| serde_json::json!({
"raid": s.raid_id,
"wave": s.wave,
"leader": s.patrol_leader,
"patrolling": s.patrolling,
"patrol_target": s.patrol_target,
"vehicle": s.vehicle,
})),
})
})
.collect();
@@ -625,7 +653,8 @@ impl Game<'_> {
self.spawn_natural();
self.tick_patrol_spawner();
self.tick_raids();
let snapshot: Vec<Seen> = self.mobs.iter().map(seen).collect();
let uuid = self.level.player_uuid;
let snapshot: Vec<Seen> = self.mobs.iter().map(|m| seen(m, uuid)).collect();
let mut events = Vec::new();
let mut mobs = std::mem::take(&mut self.mobs);
let mut dead = Vec::new();
@@ -649,6 +678,8 @@ impl Game<'_> {
}
self.mobs.append(&mut mobs);
self.sync_riders();
self.villager_reputation_tick();
self.villager_pickups();
for m in dead {
self.mob_died(&m);
}
@@ -670,6 +701,7 @@ impl Game<'_> {
self.trigger_entity("minecraft:player_killed_entity", "entity", &view);
}
self.raider_died(m, by_player);
self.villager_murdered(m, by_player);
let held = self.held().cloned();
let pos = [m.position.x, m.position.y + 0.5, m.position.z];
if !m.is_baby() {
@@ -1005,6 +1037,9 @@ impl Game<'_> {
MobEvent::CreakingTearDown { center, spread } => {
self.creaking_tear_down(center, spread)
}
MobEvent::VillagerMeet { mob, other } => self.villager_meet(mob, other),
MobEvent::VillagerBirth { parent, partner } => self.villager_birth(parent, partner),
MobEvent::GolemCheck { mob, needed } => self.villager_golem_check(mob, needed),
MobEvent::Firework { at, color, flight } => {
self.villager_firework(at, color, flight)
}
+29 -1
View File
@@ -148,7 +148,13 @@ impl Game<'_> {
}));
}
let m = &self.mobs[index];
let trade = m.extra.trade.as_deref().cloned().unwrap_or_default();
let mut trade = m.extra.trade.as_deref().cloned().unwrap_or_default();
// Villager.updateSpecialPrices: reputation and Hero of the Village.
if species == Species::Villager {
let reputation = self.villager_reputation(m.id);
merchant::update_special_prices(&mut trade.offers, reputation, self.hero_amplifier());
}
let m = &self.mobs[index];
if trade.offers.is_empty() {
let mut events = Vec::new();
villager::set_unhappy(&mut self.mobs[index], &mut events);
@@ -190,6 +196,10 @@ impl Game<'_> {
let trade = m.extra.trade.get_or_insert_default();
trade.xp = state.xp;
trade.offers = state.offers.clone();
// setTradingPlayer(null) resets the special prices.
for offer in &mut trade.offers {
offer.special_price_diff = 0;
}
}
/// 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) {
@@ -244,6 +254,16 @@ impl Game<'_> {
.map(|p| [p.position.x, p.position.y + 0.5, p.position.z]);
self.audio
.play("minecraft:entity.villager.yes", at, 1.0, 1.0);
// Villager.notifyTrade: the villager remembers the trade.
let villager = s
.merchant
.as_ref()
.filter(|m| m.progress())
.and_then(|m| m.mob);
if let Some(mob) = villager {
self.villager_traded(mob);
}
let Some(m) = s.merchant.as_mut() else { return };
if level_up {
let (profession, variant, level) =
(m.profession.clone(), m.variant.clone(), m.level + 1);
@@ -254,6 +274,14 @@ impl Game<'_> {
}
pop += 5;
}
// The prices follow the villager's new reputation.
if let Some(mob) = villager {
let reputation = self.villager_reputation(mob);
let hero = self.hero_amplifier();
if let Some(m) = s.merchant.as_mut() {
merchant::update_special_prices(&mut m.offers, reputation, hero);
}
}
if offer.reward_exp
&& let Some(at) = at
{
+467
View File
@@ -0,0 +1,467 @@
//! What villagers do with each other and with the player: gossip and
//! reputation, sharing food and wares, picking up dropped items, making
//! babies, calling iron golems and the prices they ask.
use super::Game;
use horizon_client::{
gossip::{self, GossipType},
items::ItemStack,
mobs::{Mob, Species, spawning, villager},
};
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::collections::HashMap;
fn block_of(p: Vec3) -> [i32; 3] {
[p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]
}
/// `SpawnUtil.Strategy.LEGACY_IRON_GOLEM`: what a golem will not land on.
fn golem_floor_ok(name: &str) -> bool {
!matches!(
name,
"minecraft:cobweb"
| "minecraft:cactus"
| "minecraft:glass_pane"
| "minecraft:conduit"
| "minecraft:ice"
| "minecraft:tnt"
| "minecraft:glowstone"
| "minecraft:beacon"
| "minecraft:sea_lantern"
| "minecraft:frosted_ice"
| "minecraft:tinted_glass"
| "minecraft:glass"
) && !name.ends_with("_stained_glass_pane")
&& !name.ends_with("_stained_glass")
&& !name.ends_with("leaves")
}
impl Game<'_> {
fn villager_index(&self, id: u32) -> Option<usize> {
self.mobs
.iter()
.position(|m| m.id == id && m.species() == Species::Villager)
}
fn item_max_stack(&self, item: &str) -> u32 {
self.res.items.get(item).map_or(64, |i| i.max_stack)
}
/// `BehaviorUtils.throwItem`: toss a stack from a villager's hand toward
/// a point.
fn villager_throw(&mut self, from: Vec3, eye: f64, to: Vec3, stack: ItemStack) {
let at = [from.x, eye - 0.3, from.z];
let d = Vec3::new(to.x - from.x, to.y - from.y, to.z - from.z).normalize();
self.spawn_item(stack, at, [d.x * 0.3, d.y * 0.3, d.z * 0.3], 10);
}
/// `TradeWithVillager.tick` for one pair: gossip (at most once in 1200
/// ticks for both), then surplus food and wanted wares tossed over.
pub(super) fn villager_meet(&mut self, a: u32, b: u32) {
let (Some(ia), Some(ib)) = (self.villager_index(a), self.villager_index(b)) else {
return;
};
let now = self.world.game_time;
let items = &self.res.items;
let max = |item: &str| items.get(item).map_or(64, |i| i.max_stack);
// Villager.gossip: both must be past their cool-down.
let ready = {
let ea = villager::ext(&self.mobs[ia]);
let eb = villager::ext(&self.mobs[ib]);
ea.is_none_or(|e| e.can_gossip(now)) && eb.is_none_or(|e| e.can_gossip(now))
};
let mut golem = false;
if ready {
let source = villager::ext(&self.mobs[ib]).cloned().unwrap_or_default();
let me = &mut self.mobs[ia];
let mut random = me.random.clone();
let e = villager::ext_mut(me);
e.gossips.transfer_from(&source.gossips, &mut random, 10);
e.last_gossip_time = now;
me.random = random;
villager::ext_mut(&mut self.mobs[ib]).last_gossip_time = now;
golem = true;
}
// Surplus food goes to a hungry neighbour (farmers hand it to anyone).
let farmer = villager::is_farmer(&self.mobs[ia]);
let (from, eye, to) = (
self.mobs[ia].position,
self.mobs[ia].eye_y(),
self.mobs[ib].position,
);
let wants_more = villager::ext(&self.mobs[ib]).is_none_or(|e| e.wants_more_food());
let excess = villager::ext(&self.mobs[ia]).is_some_and(|e| e.has_excess_food());
let mut thrown = Vec::new();
if excess
&& (farmer || wants_more)
&& let Some(s) = villager::ext_mut(&mut self.mobs[ia])
.take_half_stack(|s| villager::food_points(&s.item) > 0, max)
{
thrown.push(s);
}
// A farmer's wheat.
if farmer
&& villager::ext(&self.mobs[ia]).is_some_and(|e| e.count_item("minecraft:wheat") > 32)
&& let Some(s) = villager::ext_mut(&mut self.mobs[ia])
.take_half_stack(|s| &*s.item == "minecraft:wheat", max)
{
thrown.push(s);
}
// Wares the neighbour's profession asks for and ours does not.
let theirs = villager::requested_items(&self.mobs[ib]);
let mine = villager::requested_items(&self.mobs[ia]);
let wanted: Vec<&str> = theirs
.iter()
.copied()
.filter(|i| !mine.contains(i))
.collect();
if !wanted.is_empty()
&& let Some(s) = villager::ext_mut(&mut self.mobs[ia])
.take_half_stack(|s| wanted.contains(&&*s.item), max)
{
thrown.push(s);
}
for stack in thrown {
self.villager_throw(from, eye, to, stack);
}
if golem {
self.villager_golem_check(a, 5);
}
}
/// `Villager.spawnGolemIfNeeded`: when enough villagers nearby that
/// slept recently and saw no golem agree, an iron golem appears.
pub(super) fn villager_golem_check(&mut self, id: u32, needed: usize) {
let Some(i) = self.villager_index(id) else {
return;
};
let now = self.world.game_time;
if !villager::ext(&self.mobs[i]).is_some_and(|e| e.wants_golem(now)) {
return;
}
let at = self.mobs[i].position;
let nearby: Vec<usize> = self
.mobs
.iter()
.enumerate()
.filter(|(_, m)| {
m.species() == Species::Villager
&& m.alive()
&& (m.position.x - at.x).abs() <= 10.0
&& (m.position.y - at.y).abs() <= 10.0
&& (m.position.z - at.z).abs() <= 10.0
})
.map(|(j, _)| j)
.collect();
let wanting = nearby
.iter()
.filter(|j| villager::ext(&self.mobs[**j]).is_some_and(|e| e.wants_golem(now)))
.take(5)
.count();
if wanting < needed {
return;
}
if self.try_spawn_iron_golem(block_of(at)) {
for j in nearby {
villager::ext_mut(&mut self.mobs[j]).golem_until = now + 599;
}
}
}
/// `SpawnUtil.trySpawnMob(IRON_GOLEM, ..., 10 attempts, 8 across, 6 up
/// and down, LEGACY_IRON_GOLEM)`.
fn try_spawn_iron_golem(&mut self, start: [i32; 3]) -> bool {
for _ in 0..10 {
let r = &mut self.world.random;
let dx = r.next_int_bound(17).unwrap_or(8) - 8;
let dz = r.next_int_bound(17).unwrap_or(8) - 8;
let (x, z) = (start[0] + dx, start[2] + dz);
let mut y = start[1] + 6;
let mut above = self.world.block(x, y, z);
let mut found = None;
for _ in 0..=12 {
y -= 1;
let here = self.world.block(x, y, z);
let f = self.res.facts.get(here);
let above_f = self.res.facts.get(above);
let air_or_liquid = self.res.facts.is_air(above)
|| above_f.fluid != horizon_client::blocks::Fluid::None;
let solid = self.res.mob_data.state(here).flags & horizon_client::mobs::data::SOLID
!= 0
|| f.name.as_ref() == "minecraft:powder_snow";
if golem_floor_ok(&f.name) && air_or_liquid && solid {
found = Some(y + 1);
break;
}
above = here;
}
let Some(y) = found else { continue };
// IronGolem.checkSpawnRules: a floor and three free blocks.
let free = |g: &Self, yy: i32| {
g.res.mob_data.state(g.world.block(x, yy, z)).flags
& horizon_client::mobs::data::VALID_EMPTY_SPAWN
!= 0
};
if !(0..4).all(|k| free(self, y + k)) {
continue;
}
let at = [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5];
if let Some(id) = self.spawn_mob_for("minecraft:iron_golem", at, false, true)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
let sound = m.kind.sounds[0];
if !sound.is_empty() {
let at = m.center();
self.audio
.play(&format!("minecraft:{sound}"), Some(at), 1.0, 1.0);
}
return true;
}
}
false
}
/// `VillagerMakeLove.tryToGiveBirth`: both eat, a free bed within 48
/// blocks is taken for the child, who is a baby villager of one of
/// three villager types.
pub(super) fn villager_birth(&mut self, parent: u32, partner: u32) {
let (Some(ia), Some(ib)) = (self.villager_index(parent), self.villager_index(partner))
else {
return;
};
villager::ext_mut(&mut self.mobs[ia]).eat_and_digest();
villager::ext_mut(&mut self.mobs[ib]).eat_and_digest();
let from = self.mobs[ia].position;
let angry = |g: &mut Self| {
for i in [ia, ib] {
let p = g.mobs[i].position;
g.particles_at("angry_villager", [p.x, p.y + 1.8, p.z]);
}
};
let Some(bed) = self.take_vacant_bed(block_of(from)) else {
angry(self);
return;
};
// Villager.getBreedOffspring: half the biome's type, a quarter each parent's.
let roll = self.mobs[ia].random.next_double();
let kind_of = |m: &Mob| m.extra.variant;
let facts = self.biome_facts(
from.x.floor() as i32,
from.y.floor() as i32,
from.z.floor() as i32,
);
let variant = if roll < 0.5 {
spawning::villager_type(&facts)
} else if roll < 0.75 {
kind_of(&self.mobs[ia])
} else {
kind_of(&self.mobs[ib])
};
let Some(id) =
self.spawn_mob_for("minecraft:villager", [from.x, from.y, from.z], true, true)
else {
return;
};
self.mobs[ia].extra.age = 6000;
self.mobs[ib].extra.age = 6000;
if let Some(child) = self.mobs.iter_mut().find(|m| m.id == id) {
child.extra.variant = variant;
child.extra.variant2 = villager::NONE;
child.extra.age = -24000;
child.extra.bed = Some(bed);
}
self.particles_at("heart", [from.x, from.y + 1.8, from.z]);
}
/// `PoiManager.take(HOME, ..., 48)`: the nearest unclaimed bed head.
fn take_vacant_bed(&self, from: [i32; 3]) -> Option<[i32; 3]> {
let claimed: Vec<[i32; 3]> = self
.mobs
.iter()
.filter(|m| m.species() == Species::Villager)
.filter_map(|m| m.extra.bed)
.collect();
let mut known: HashMap<u32, bool> = HashMap::new();
let mut best: Option<(i32, [i32; 3])> = None;
for y in from[1] - 8..=from[1] + 8 {
for z in from[2] - 48..=from[2] + 48 {
for x in from[0] - 48..=from[0] + 48 {
let state = self.world.block(x, y, z);
if self.res.facts.is_air(state) {
continue;
}
let free_head = *known.entry(state.0).or_insert_with(|| {
self.res.facts.get(state).name.ends_with("_bed")
&& self.res.assets.registry.state(state).is_some_and(|s| {
s.properties.get("part").map(String::as_str) == Some("head")
&& s.properties.get("occupied").map(String::as_str)
!= Some("true")
})
});
let d = (x - from[0]).pow(2) + (y - from[1]).pow(2) + (z - from[2]).pow(2);
if free_head
&& d <= 48 * 48
&& !claimed.contains(&[x, y, z])
&& best.is_none_or(|(b, _)| d < b)
{
best = Some((d, [x, y, z]));
}
}
}
}
best.map(|(_, p)| p)
}
fn particles_at(&mut self, kind: &'static str, at: [f64; 3]) {
if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) {
let options = horizon_client::particles::ParticleOptions::simple(ty);
self.particles.add(&options, at, [0.0; 3]);
}
}
/// `Mob.aiStep` item pickup for villagers (`InventoryCarrier`): food,
/// seeds and what their profession wants, from within a block.
pub(super) fn villager_pickups(&mut self) {
if self.dropped.is_empty() || !self.ui.rules.bool("mob_griefing") {
return;
}
let picks_up = self
.res
.items
.item_tags
.get("minecraft:villager_picks_up")
.cloned();
for i in 0..self.mobs.len() {
let m = &self.mobs[i];
if m.species() != Species::Villager || !m.alive() {
continue;
}
let (pos, half) = (m.position, f64::from(m.width()) / 2.0 + 1.0);
let top = f64::from(m.height());
let requested = villager::requested_items(m);
let mut j = 0;
while j < self.dropped.len() {
let e = &self.dropped[j];
let near = (e.position.x - pos.x).abs() <= half
&& (e.position.z - pos.z).abs() <= half
&& e.position.y >= pos.y - 0.25
&& e.position.y <= pos.y + top;
let item = e.stack.item.clone();
let wants = villager::food_points(&item) > 0
|| picks_up.as_ref().is_some_and(|t| t.contains(&*item))
|| requested.contains(&&*item);
if !near || e.pickup_delay > 0 || !wants {
j += 1;
continue;
}
let max = self.item_max_stack(&item);
let stack = self.dropped[j].stack.clone();
if !villager::ext_mut(&mut self.mobs[i]).can_add(&stack, max) {
j += 1;
continue;
}
let rest = villager::ext_mut(&mut self.mobs[i]).add_item(stack, max);
match rest {
None => {
self.dropped.remove(j);
}
Some(rest) => {
self.dropped[j].stack.count = rest.count;
j += 1;
}
}
}
}
}
/// `Villager.setLastHurtByMob` and `ServerLevel.onReputationEvent`: a hit
/// from the player counts against it with the villager that was hit.
pub(super) fn villager_reputation_tick(&mut self) {
let Some(uuid) = self.level.player_uuid else {
return;
};
let mut angry = Vec::new();
for m in &mut self.mobs {
if m.species() != Species::Villager
|| m.ai.last_hurt_by != Some(horizon_client::mobs::Who::Player)
{
continue;
}
let time = m.ai.last_hurt_by_time;
let alive = m.alive();
let at = m.position;
let e = villager::ext_mut(m);
if e.hurt_seen != time {
e.hurt_seen = time;
e.gossips.add(
uuid,
GossipType::MinorNegative,
gossip::REPUTATION_CHANGE_PER_EVENT,
);
if alive {
angry.push(at);
}
}
}
for at in angry {
self.particles_at("angry_villager", [at.x, at.y + 1.8, at.z]);
}
}
/// `Villager.tellWitnessesThatIWasMurdered`: the villagers that saw a
/// player kill one remember it as a major wrong.
pub(super) fn villager_murdered(&mut self, victim: &Mob, by_player: bool) {
if victim.species() != Species::Villager || !by_player {
return;
}
let Some(uuid) = self.level.player_uuid else {
return;
};
let eye = Vec3::new(victim.position.x, victim.eye_y(), victim.position.z);
let witnesses: Vec<usize> = {
let w = self.mob_world_base(&[]);
self.mobs
.iter()
.enumerate()
.filter(|(_, m)| {
m.id != victim.id
&& m.species() == Species::Villager
&& m.alive()
&& (m.position.x - victim.position.x).abs() <= 16.0
&& (m.position.y - victim.position.y).abs() <= 16.0
&& (m.position.z - victim.position.z).abs() <= 16.0
&& w.line_of_sight(eye, Vec3::new(m.position.x, m.eye_y(), m.position.z))
})
.map(|(i, _)| i)
.collect()
};
for i in witnesses {
villager::ext_mut(&mut self.mobs[i]).gossips.add(
uuid,
GossipType::MajorNegative,
gossip::REPUTATION_CHANGE_PER_EVENT,
);
}
}
/// `ReputationEventType.TRADE`: each trade earns a little trust.
pub(super) fn villager_traded(&mut self, id: u32) {
let Some(uuid) = self.level.player_uuid else {
return;
};
let Some(i) = self.villager_index(id) else {
return;
};
villager::ext_mut(&mut self.mobs[i]).gossips.add(
uuid,
GossipType::Trading,
gossip::REPUTATION_CHANGE_PER_TRADE,
);
let p = self.mobs[i].position;
self.particles_at("happy_villager", [p.x, p.y + 1.8, p.z]);
}
/// `Villager.getPlayerReputation` of the local player.
pub(super) fn villager_reputation(&self, id: u32) -> i32 {
let Some(uuid) = self.level.player_uuid else {
return 0;
};
self.villager_index(id)
.and_then(|i| villager::ext(&self.mobs[i]))
.map_or(0, |e| e.gossips.reputation(uuid))
}
/// The Hero of the Village amplifier of the player, if any.
pub(super) fn hero_amplifier(&self) -> Option<i32> {
self.potions.effects.amplifier("hero_of_the_village")
}
}
+386
View File
@@ -0,0 +1,386 @@
//! Villager gossip (`GossipContainer` and `GossipType`): what a villager
//! remembers about each player, how it fades by the day, how it spreads from
//! villager to villager and the reputation it adds up to.
use horizon_core::random::{LegacyRandom, RandomSource};
use horizon_world::nbt::Tag;
use std::collections::BTreeMap;
/// `ReputationEventType` amounts.
pub const REPUTATION_CHANGE_PER_EVENT: i32 = 25;
pub const REPUTATION_CHANGE_PER_EVERLASTING_MEMORY: i32 = 20;
pub const REPUTATION_CHANGE_PER_TRADE: i32 = 2;
/// `GossipContainer.DISCARD_THRESHOLD`: values below this are forgotten.
const DISCARD_THRESHOLD: i32 = 2;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum GossipType {
MajorNegative,
MinorNegative,
MinorPositive,
MajorPositive,
Trading,
}
impl GossipType {
pub const ALL: [Self; 5] = [
Self::MajorNegative,
Self::MinorNegative,
Self::MinorPositive,
Self::MajorPositive,
Self::Trading,
];
pub fn id(self) -> &'static str {
match self {
Self::MajorNegative => "major_negative",
Self::MinorNegative => "minor_negative",
Self::MinorPositive => "minor_positive",
Self::MajorPositive => "major_positive",
Self::Trading => "trading",
}
}
pub fn from_id(id: &str) -> Option<Self> {
Self::ALL.into_iter().find(|t| t.id() == id)
}
fn index(self) -> usize {
self as usize
}
pub fn weight(self) -> i32 {
match self {
Self::MajorNegative => -5,
Self::MinorNegative => -1,
Self::MinorPositive => 1,
Self::MajorPositive => 5,
Self::Trading => 1,
}
}
pub fn max(self) -> i32 {
match self {
Self::MajorNegative => 100,
Self::MinorNegative => 200,
Self::MinorPositive | Self::Trading => 25,
Self::MajorPositive => 20,
}
}
pub fn decay_per_day(self) -> i32 {
match self {
Self::MajorNegative => 10,
Self::MinorNegative => 20,
Self::MinorPositive => 1,
Self::MajorPositive => 0,
Self::Trading => 2,
}
}
pub fn decay_per_transfer(self) -> i32 {
match self {
Self::MajorNegative => 10,
Self::MinorNegative => 20,
Self::MinorPositive => 5,
Self::MajorPositive | Self::Trading => 20,
}
}
}
/// A UUID as four ints.
pub type Target = [i32; 4];
/// One gossip entry (`GossipContainer.GossipEntry`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Entry {
target: Target,
kind: GossipType,
value: i32,
}
impl Entry {
fn weighted(self) -> i32 {
self.value * self.kind.weight()
}
}
/// `GossipContainer`: per target, the value of each gossip type (0: none).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Gossips {
map: BTreeMap<Target, [i32; 5]>,
}
impl Gossips {
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn clear(&mut self) {
self.map.clear();
}
pub fn get(&self, target: Target, kind: GossipType) -> i32 {
self.map.get(&target).map_or(0, |e| e[kind.index()])
}
/// `getReputation`: the weighted sum of every type for a target.
pub fn reputation(&self, target: Target) -> i32 {
self.map.get(&target).map_or(0, |e| {
GossipType::ALL
.into_iter()
.map(|t| e[t.index()] * t.weight())
.sum()
})
}
/// How many targets have a gossip of `kind` whose weighted value passes `test`.
pub fn count_for_type(&self, kind: GossipType, test: impl Fn(f64) -> bool) -> usize {
self.map
.values()
.filter(|e| test(f64::from(e[kind.index()] * kind.weight())))
.count()
}
/// `add`: sums up to the type's maximum and forgets values below 2.
pub fn add(&mut self, target: Target, kind: GossipType, amount: i32) {
let entries = self.map.entry(target).or_insert([0; 5]);
let old = entries[kind.index()];
entries[kind.index()] = if old == 0 {
amount
} else {
let sum = old + amount;
if sum > kind.max() {
kind.max().max(old)
} else {
sum
}
};
let value = entries[kind.index()];
if value > kind.max() {
entries[kind.index()] = kind.max();
}
if value < DISCARD_THRESHOLD {
entries[kind.index()] = 0;
}
if entries.iter().all(|v| *v == 0) {
self.map.remove(&target);
}
}
pub fn remove(&mut self, target: Target, kind: GossipType) {
if let Some(e) = self.map.get_mut(&target) {
e[kind.index()] = 0;
if e.iter().all(|v| *v == 0) {
self.map.remove(&target);
}
}
}
/// `decay` (once per day): every type loses its daily amount.
pub fn decay(&mut self) {
self.map.retain(|_, e| {
for kind in GossipType::ALL {
let v = e[kind.index()];
if v == 0 {
continue;
}
let next = v - kind.decay_per_day();
e[kind.index()] = if next < DISCARD_THRESHOLD { 0 } else { next };
}
e.iter().any(|v| *v != 0)
});
}
fn unpack(&self) -> Vec<Entry> {
let mut out = Vec::new();
for (target, e) in &self.map {
for kind in GossipType::ALL {
if e[kind.index()] != 0 {
out.push(Entry {
target: *target,
kind,
value: e[kind.index()],
});
}
}
}
out
}
/// `selectGossipsForTransfer`: `max_count` picks weighted by magnitude,
/// duplicates counted once.
fn select_for_transfer(&self, random: &mut LegacyRandom, max_count: usize) -> Vec<Entry> {
let entries = self.unpack();
if entries.is_empty() {
return Vec::new();
}
let mut ends = Vec::with_capacity(entries.len());
let mut total = 0;
for e in &entries {
total += e.weighted().abs();
ends.push(total - 1);
}
let mut picked: Vec<usize> = Vec::new();
for _ in 0..max_count {
let choice = random.next_int_bound(total).unwrap_or(0);
// Arrays.binarySearch on the strictly increasing range ends.
let index = match ends.binary_search(&choice) {
Ok(i) | Err(i) => i,
};
if !picked.contains(&index) {
picked.push(index);
}
}
picked.into_iter().map(|i| entries[i]).collect()
}
/// `transferFrom`: gossip heard from another villager, weakened by the
/// retelling. Returns how many gossips were picked.
pub fn transfer_from(
&mut self,
source: &Gossips,
random: &mut LegacyRandom,
max_count: usize,
) -> usize {
let picked = source.select_for_transfer(random, max_count);
for g in &picked {
let decayed = g.value - g.kind.decay_per_transfer();
if decayed >= DISCARD_THRESHOLD {
let e = self.map.entry(g.target).or_insert([0; 5]);
let slot = &mut e[g.kind.index()];
*slot = (*slot).max(decayed);
}
}
picked.len()
}
pub fn to_nbt(&self) -> Tag {
Tag::List(
self.unpack()
.into_iter()
.map(|e| {
Tag::compound([
("Target", Tag::IntArray(e.target.to_vec())),
("Type", Tag::String(e.kind.id().into())),
("Value", Tag::Int(e.value)),
])
})
.collect(),
)
}
pub fn from_nbt(tag: &Tag) -> Self {
let mut out = Self::default();
let Tag::List(list) = tag else { return out };
for g in list {
let target = match g.get("Target") {
Some(Tag::IntArray(v)) if v.len() == 4 => [v[0], v[1], v[2], v[3]],
_ => continue,
};
let kind = match g.get("Type") {
Some(Tag::String(s)) => GossipType::from_id(&s.to_string_lossy()),
_ => None,
};
let value = match g.get("Value") {
Some(Tag::Int(v)) => *v,
_ => continue,
};
if let Some(kind) = kind
&& value > 0
{
out.map.entry(target).or_insert([0; 5])[kind.index()] = value;
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
const PLAYER: Target = [1, 2, 3, 4];
const OTHER: Target = [5, 6, 7, 8];
#[test]
fn reputation_adds_up_weighted() {
let mut g = Gossips::default();
g.add(PLAYER, GossipType::MinorPositive, 25);
g.add(PLAYER, GossipType::MajorPositive, 20);
g.add(PLAYER, GossipType::Trading, 2);
// 25 + 20 * 5 + 2
assert_eq!(g.reputation(PLAYER), 127);
g.add(PLAYER, GossipType::MajorNegative, 25);
assert_eq!(g.reputation(PLAYER), 127 - 125);
assert_eq!(g.reputation(OTHER), 0);
}
#[test]
fn values_stop_at_their_maximum() {
let mut g = Gossips::default();
for _ in 0..10 {
g.add(PLAYER, GossipType::MajorNegative, 25);
}
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 100);
// The minor negative cap is 200: eight hits of 25 fill it.
for _ in 0..12 {
g.add(PLAYER, GossipType::MinorNegative, 25);
}
assert_eq!(g.get(PLAYER, GossipType::MinorNegative), 200);
assert_eq!(g.reputation(PLAYER), -500 - 200);
}
#[test]
fn small_values_are_forgotten() {
let mut g = Gossips::default();
g.add(PLAYER, GossipType::Trading, 1);
assert!(g.is_empty());
g.add(PLAYER, GossipType::Trading, 2);
assert_eq!(g.get(PLAYER, GossipType::Trading), 2);
g.remove(PLAYER, GossipType::Trading);
assert!(g.is_empty());
}
#[test]
fn gossip_decays_by_the_day() {
let mut g = Gossips::default();
g.add(PLAYER, GossipType::MajorNegative, 25);
g.add(PLAYER, GossipType::MinorNegative, 25);
g.add(PLAYER, GossipType::MinorPositive, 3);
g.add(PLAYER, GossipType::MajorPositive, 20);
g.decay();
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 15);
assert_eq!(g.get(PLAYER, GossipType::MinorNegative), 5);
assert_eq!(g.get(PLAYER, GossipType::MinorPositive), 2);
// Major positive gossip never fades.
assert_eq!(g.get(PLAYER, GossipType::MajorPositive), 20);
g.decay();
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 5);
assert_eq!(g.get(PLAYER, GossipType::MinorNegative), 0);
assert_eq!(g.get(PLAYER, GossipType::MinorPositive), 0);
g.decay();
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 0);
assert_eq!(g.len(), 1);
}
#[test]
fn retold_gossip_is_weaker() {
let mut source = Gossips::default();
source.add(PLAYER, GossipType::MajorNegative, 25);
source.add(OTHER, GossipType::Trading, 25);
let mut heard = Gossips::default();
let mut random = LegacyRandom::new(11);
let n = heard.transfer_from(&source, &mut random, 50);
assert!((1..=2).contains(&n));
// 25 - 10 per transfer for major negative, 25 - 20 for trading.
let major = heard.get(PLAYER, GossipType::MajorNegative);
let trading = heard.get(OTHER, GossipType::Trading);
assert!(major == 0 || major == 15);
assert!(trading == 0 || trading == 5);
assert!(major + trading > 0);
// A second hearing keeps the stronger value.
heard.transfer_from(&source, &mut random, 50);
assert!(heard.get(PLAYER, GossipType::MajorNegative) <= 15);
// Gossip too weak to survive retelling is dropped.
let mut faint = Gossips::default();
faint.add(PLAYER, GossipType::Trading, 5);
let mut heard = Gossips::default();
heard.transfer_from(&faint, &mut random, 10);
assert!(heard.is_empty());
}
#[test]
fn gossip_round_trips_through_nbt() {
let mut g = Gossips::default();
g.add(PLAYER, GossipType::MajorNegative, 25);
g.add(PLAYER, GossipType::Trading, 2);
g.add(OTHER, GossipType::MinorPositive, 25);
assert_eq!(Gossips::from_nbt(&g.to_nbt()), g);
}
#[test]
fn counts_by_type() {
let mut g = Gossips::default();
g.add(PLAYER, GossipType::MajorNegative, 25);
g.add(OTHER, GossipType::MajorNegative, 25);
g.add(OTHER, GossipType::Trading, 25);
assert_eq!(g.count_for_type(GossipType::MajorNegative, |v| v < 0.0), 2);
assert_eq!(g.count_for_type(GossipType::Trading, |v| v < 0.0), 0);
}
}
+1
View File
@@ -30,6 +30,7 @@ pub mod fog;
pub mod font;
pub mod gamerules;
pub mod gfx;
pub mod gossip;
pub mod health;
pub mod hud;
pub mod hunger;
+43
View File
@@ -98,6 +98,23 @@ impl Trader {
}
}
/// `Villager.updateSpecialPrices`: the reputation and Hero of the Village
/// discounts of a player, from scratch.
pub fn update_special_prices(offers: &mut [MerchantOffer], reputation: i32, hero: Option<i32>) {
// 0.3F + 0.0625F * amplifier, widened from float.
let hero_modifier = hero.map_or(0.0, |a| f64::from(0.3f32 + 0.0625f32 * a as f32));
for offer in offers {
offer.special_price_diff = 0;
if reputation != 0 {
offer.special_price_diff -= (reputation as f32 * offer.price_multiplier).floor() as i32;
}
if hero_modifier > 0.0 {
let reduction =
(hero_modifier * f64::from(offer.base_cost_a.stack.count)).floor() as i32;
offer.special_price_diff -= reduction.max(1);
}
}
}
/// 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)]
@@ -708,6 +725,32 @@ mod tests {
assert!(!can_level_up(5));
}
#[test]
fn reputation_and_heroes_lower_prices() {
let items = items();
let mut offers = vec![offer(10, None), offer(1, None)];
// Reputation 50 with a 0.2 multiplier: 10 off, floored per offer.
update_special_prices(&mut offers, 50, None);
assert_eq!(offers[0].special_price_diff, -10);
assert_eq!(offers[0].cost_a_count(&items), 1);
assert_eq!(offers[1].special_price_diff, -10);
// Bad reputation raises the price (-30 * 0.2 = -6 floors to -6).
update_special_prices(&mut offers, -30, None);
assert_eq!(offers[0].special_price_diff, 6);
assert_eq!(offers[0].cost_a_count(&items), 16);
// Hero of the Village I: 0.3 * 10 = 3 off, at least 1.
update_special_prices(&mut offers, 0, Some(0));
assert_eq!(offers[0].special_price_diff, -3);
assert_eq!(offers[1].special_price_diff, -1);
// Level III: 0.3 + 0.125 = 0.425 -> 4 off a ten emerald price.
update_special_prices(&mut offers, 0, Some(2));
assert_eq!(offers[0].special_price_diff, -4);
// Both stack, from scratch each time.
update_special_prices(&mut offers, 25, Some(0));
assert_eq!(offers[0].special_price_diff, -5 - 3);
update_special_prices(&mut offers, 0, None);
assert_eq!(offers[0].special_price_diff, 0);
}
#[test]
fn offers_follow_the_trade_data() {
let items = items();
+19
View File
@@ -665,6 +665,21 @@ pub enum MobEvent {
kind: DamageKind,
amount: f32,
},
/// Two villagers are close: swap gossip and share food and wares.
VillagerMeet {
mob: u32,
other: u32,
},
/// Two villagers make a baby.
VillagerBirth {
parent: u32,
partner: u32,
},
/// A villager asks whether enough neighbours want an iron golem.
GolemCheck {
mob: u32,
needed: usize,
},
/// A villager launches a firework rocket (celebrating a won raid).
Firework {
at: [f64; 3],
@@ -745,6 +760,8 @@ pub struct Seen {
pub bed: Option<[i32; 3]>,
/// A raider in an active raid.
pub active_raid: bool,
/// A villager's reputation of the player (`getPlayerReputation`).
pub player_rep: i32,
}
/// The player as mobs see it.
#[derive(Clone, Debug)]
@@ -769,6 +786,8 @@ pub struct PlayerView {
pub last_hurt: Option<(Who, i64)>,
/// The Hero of the Village effect.
pub hero: bool,
/// The player's UUID (villagers' gossip is keyed by it).
pub uuid: [i32; 4],
}
pub struct MobWorld<'a> {
pub world: &'a World,
+43
View File
@@ -36,6 +36,7 @@ pub fn register_iron(m: &mut Mob) {
);
g.add(7, LookAtPlayer::new(6.0));
g.add(8, RandomLookAround::default());
m.ai.targets.add(1, DefendVillage);
m.ai.targets.add(2, HurtByTarget::new());
m.ai.targets.add(
3,
@@ -48,6 +49,48 @@ pub fn register_iron(m: &mut Mob) {
NearestTarget::new(Prey::Filter(golem_prey), false).interval(5),
);
}
/// `DefendVillageTargetGoal`: a player that a villager nearby has no
/// good word for (reputation of -100 or worse) is attacked on sight.
#[derive(Clone, Debug)]
struct DefendVillage;
impl Goal for DefendVillage {
goal_clone!();
fn flags(&self) -> u8 {
super::goals::TARGET
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(p) = &cx.w.player else { return false };
if !p.alive || p.creative || p.spectator {
return false;
}
// The box around the golem: 10 across, 8 up and down.
let b = m.bounds().inflate(Vec3::new(10.0, 8.0, 10.0));
if !b.intersects(p.bounds) || m.position.distance_squared(p.position) > 64.0 * 64.0 {
return false;
}
let bad = cx.w.others.iter().any(|s| {
s.species == Species::Villager
&& s.alive
&& s.player_rep <= -100
&& b.contains(s.position)
&& s.position.distance_squared(m.position) <= 64.0 * 64.0
});
bad && m.sees(cx.w, Who::Player)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
m.target_info(cx.w).is_some_and(|t| {
t.alive
&& !(t.is_player && t.creative)
&& m.position.distance_squared(t.position) <= 64.0 * 64.0
})
}
fn start(&mut self, m: &mut Mob, _cx: &mut Cx) {
m.ai.target = Some(Who::Player);
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
m.ai.target = None;
}
}
/// `MoveTowardsTargetGoal`: close in on a target within range.
#[derive(Clone, Debug)]
struct MoveTowardsTarget {
+564
View File
@@ -12,6 +12,7 @@ use super::{
Stroll, goal_clone,
},
};
use crate::items::ItemStack;
use horizon_core::random::RandomSource;
use std::{collections::HashMap, f32::consts::PI};
@@ -75,6 +76,8 @@ pub fn register(m: &mut Mob) {
);
g.add(1, Panic::new(0.75));
g.add(2, RaidBehavior::default());
g.add(3, Social::default());
g.add(0, GolemCall);
g.add(3, GiftToHero::default());
g.add(3, JobSite::default());
g.add(3, AcquireHome::default());
@@ -458,6 +461,7 @@ fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) {
_ => 4,
};
m.nav_stop();
ext_mut(m).last_slept = Some(w.game_time);
m.velocity = horizon_core::geometry::Vec3::ZERO;
m.position = horizon_core::geometry::Vec3::new(
f64::from(p[0]) + 0.5,
@@ -518,6 +522,23 @@ 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 {
let now = w.game_time;
let seen_golem = (i64::from(m.age) + i64::from(m.id)) % 200 == 0
&& w.others.iter().any(|s| {
s.species == Species::IronGolem
&& s.alive
&& (s.position.x - m.position.x).abs() <= 16.0
&& (s.position.y - m.position.y).abs() <= 16.0
&& (s.position.z - m.position.z).abs() <= 16.0
});
let e = ext_mut(m);
// Villager.maybeDecayGossip and the GolemSensor (every 200 ticks).
e.maybe_decay(now);
if seen_golem {
e.golem_until = now + 599;
}
}
// WakeUp / LivingEntity.hurt: morning, a hit or a missing bed.
if sleeping(m) {
let bed_gone = m
@@ -612,6 +633,20 @@ pub const RAID_VICTORY: u8 = 3;
pub struct Ext {
/// Which raid package the villager follows.
pub raid: u8,
/// What the villager remembers of players (`gossips`).
pub gossips: crate::gossip::Gossips,
pub last_gossip_time: i64,
pub last_gossip_decay: i64,
/// `foodLevel`: eaten but not yet digested, in food points.
pub food_level: i32,
/// The eight-slot inventory (`InventoryCarrier`).
pub inventory: Vec<ItemStack>,
/// `LAST_SLEPT` memory.
pub last_slept: Option<i64>,
/// `GOLEM_DETECTED_RECENTLY` expires at this game time.
pub golem_until: i64,
/// The `last_hurt_by_time` of the player's hit already counted.
pub hurt_seen: i32,
}
pub fn ext(m: &Mob) -> Option<&Ext> {
m.extra.villager.as_deref()
@@ -809,3 +844,532 @@ impl Goal for GiftToHero {
}
}
}
// ---- Gossip, food, breeding and golems.
/// `VillagerFood` nutrition (`DataComponents.VILLAGER_FOOD`).
pub fn food_points(item: &str) -> i32 {
match item {
"minecraft:bread" => 4,
"minecraft:potato" | "minecraft:carrot" | "minecraft:beetroot" => 1,
_ => 0,
}
}
/// The farmer's `requestedItems`.
pub fn farmer_items() -> &'static [&'static str] {
&[
"minecraft:bread",
"minecraft:potato",
"minecraft:carrot",
"minecraft:wheat",
"minecraft:wheat_seeds",
"minecraft:beetroot",
"minecraft:beetroot_seeds",
"minecraft:torchflower_seeds",
"minecraft:pitcher_pod",
]
}
/// A villager's `requestedItems` by profession.
pub fn requested_items(m: &Mob) -> &'static [&'static str] {
if super::render::PROFESSIONS[m.extra.variant2 as usize % 15] == "farmer" {
farmer_items()
} else {
&[]
}
}
pub fn is_farmer(m: &Mob) -> bool {
super::render::PROFESSIONS[m.extra.variant2 as usize % 15] == "farmer"
}
/// `SimpleContainer(8)`: stacks the villager carries.
const INVENTORY_SLOTS: usize = 8;
impl Ext {
/// `countFoodPointsInInventory`.
pub fn food_in_inventory(&self) -> i32 {
self.inventory
.iter()
.map(|s| food_points(&s.item) * s.count as i32)
.sum()
}
/// `hasExcessFood` and `wantsMoreFood`.
pub fn has_excess_food(&self) -> bool {
self.food_in_inventory() >= 24
}
pub fn wants_more_food(&self) -> bool {
self.food_in_inventory() < 12
}
fn hungry(&self) -> bool {
self.food_level < 12
}
/// `Villager.eatAndDigestFood`: eat until full, then digest 12 points.
pub fn eat_and_digest(&mut self) {
if self.hungry() {
let mut slot = 0;
while slot < self.inventory.len() && self.hungry() {
let points = food_points(&self.inventory[slot].item);
if points > 0 {
while self.inventory[slot].count > 0 && self.hungry() {
self.food_level += points;
self.inventory[slot].count -= 1;
}
if self.inventory[slot].count == 0 {
self.inventory.remove(slot);
continue;
}
}
slot += 1;
}
}
self.food_level -= 12;
}
/// Whether the stack fits (`SimpleContainer.canAddItem`).
pub fn can_add(&self, stack: &ItemStack, max_stack: u32) -> bool {
self.inventory.len() < INVENTORY_SLOTS
|| self
.inventory
.iter()
.any(|s| s.same_item_same_components(stack) && s.count < max_stack)
}
/// `SimpleContainer.addItem`: merge into stacks, then free slots; the
/// part that did not fit is returned.
pub fn add_item(&mut self, mut stack: ItemStack, max_stack: u32) -> Option<ItemStack> {
for s in &mut self.inventory {
if stack.count > 0 && s.same_item_same_components(&stack) && s.count < max_stack {
let n = (max_stack - s.count).min(stack.count);
s.count += n;
stack.count -= n;
}
}
while stack.count > 0 && self.inventory.len() < INVENTORY_SLOTS {
let n = stack.count.min(max_stack);
self.inventory.push(ItemStack {
count: n,
..stack.clone()
});
stack.count -= n;
}
(stack.count > 0).then_some(stack)
}
pub fn count_item(&self, item: &str) -> u32 {
self.inventory
.iter()
.filter(|s| &*s.item == item)
.map(|s| s.count)
.sum()
}
/// `TradeWithVillager.throwHalfStack`: the half of a big matching stack
/// (or whatever is over 24) leaves the inventory.
pub fn take_half_stack(
&mut self,
wanted: impl Fn(&ItemStack) -> bool,
max_stack: impl Fn(&str) -> u32,
) -> Option<ItemStack> {
for i in 0..self.inventory.len() {
let s = &self.inventory[i];
if s.count == 0 || !wanted(s) {
continue;
}
let count = if s.count > max_stack(&s.item) / 2 {
s.count / 2
} else if s.count > 24 {
s.count - 24
} else {
continue;
};
let taken = ItemStack { count, ..s.clone() };
self.inventory[i].count -= count;
if self.inventory[i].count == 0 {
self.inventory.remove(i);
}
return Some(taken);
}
None
}
/// `Villager.wantsToSpawnGolem`: slept within the last day and no golem
/// seen lately.
pub fn wants_golem(&self, now: i64) -> bool {
self.last_slept.is_some_and(|t| now - t < 24000) && now >= self.golem_until
}
/// `maybeDecayGossip`: once a day.
pub fn maybe_decay(&mut self, now: i64) {
if self.last_gossip_decay == 0 {
self.last_gossip_decay = now;
} else if now >= self.last_gossip_decay + 24000 {
self.gossips.decay();
self.last_gossip_decay = now;
}
}
/// `Villager.gossip` timing: hearing again waits 1200 ticks.
pub fn can_gossip(&self, now: i64) -> bool {
now < self.last_gossip_time || now >= self.last_gossip_time + 1200
}
}
/// `Villager.canBreed`: enough food, awake and an adult.
pub fn can_breed(m: &Mob) -> bool {
m.species() == Species::Villager
&& m.extra.age == 0
&& !sleeping(m)
&& ext(m).map_or(0, |e| e.food_level + e.food_in_inventory()) >= 12
}
/// The saved fields (`FoodLevel`, `Gossips`, `LastGossipDecay`, `Inventory`
/// and the sleep and golem memories).
pub fn write_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) {
use horizon_world::nbt::Tag;
let Some(e) = ext(m) else { return };
map.insert(
"FoodLevel".into(),
Tag::Byte(e.food_level.clamp(-128, 127) as i8),
);
map.insert("Gossips".into(), e.gossips.to_nbt());
map.insert("LastGossipDecay".into(), Tag::Long(e.last_gossip_decay));
map.insert(
"Inventory".into(),
Tag::List(e.inventory.iter().map(crate::save::item_to_nbt).collect()),
);
}
/// The memories of `Brain.memories` the villager keeps besides positions.
pub fn write_memories(m: &Mob, memories: &mut Vec<(&'static str, horizon_world::nbt::Tag)>) {
use horizon_world::nbt::Tag;
let Some(e) = ext(m) else { return };
if let Some(t) = e.last_slept {
memories.push((
"minecraft:last_slept",
Tag::compound([("value", Tag::Long(t))]),
));
}
}
pub fn read_nbt(m: &mut Mob, tag: &horizon_world::nbt::Tag) {
use horizon_world::nbt::Tag;
let int = |t: Option<&Tag>| match t {
Some(Tag::Int(v)) => Some(i64::from(*v)),
Some(Tag::Byte(v)) => Some(i64::from(*v)),
Some(Tag::Short(v)) => Some(i64::from(*v)),
Some(Tag::Long(v)) => Some(*v),
_ => None,
};
let last_slept = int(tag
.get("Brain")
.and_then(|b| b.get("memories"))
.and_then(|b| b.get("minecraft:last_slept"))
.and_then(|j| j.get("value")));
let e = ext_mut(m);
e.food_level = int(tag.get("FoodLevel")).unwrap_or(0) as i32;
e.gossips = tag
.get("Gossips")
.map(crate::gossip::Gossips::from_nbt)
.unwrap_or_default();
e.last_gossip_decay = int(tag.get("LastGossipDecay")).unwrap_or(0);
e.last_slept = last_slept;
if let Some(Tag::List(items)) = tag.get("Inventory") {
e.inventory = items
.iter()
.filter_map(crate::save::item_from_nbt)
.take(INVENTORY_SLOTS)
.collect();
}
}
/// `InteractWith(VILLAGER)`, `TradeWithVillager` and `VillagerMakeLove` while
/// idle, and `SocializeAtBell` at the meeting: walk up to a villager, swap
/// gossip and food, and make a baby with a willing partner.
#[derive(Clone, Debug, Default)]
struct Social {
target: Option<u32>,
breed: bool,
ticks: i32,
cooldown: i32,
birth_at: i64,
}
impl Social {
fn pick(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let breedable = can_breed(m);
let id = m.id;
let nearest =
cx.w.nearby(m.position, 8.0, move |s| {
s.species == Species::Villager && s.id != id
})
.filter(|s| m.position.distance_squared(s.position) <= 64.0)
.map(|s| (s.id, s.in_love))
.collect::<Vec<_>>();
let visible: Vec<(u32, bool)> = nearest
.into_iter()
.filter(|(i, _)| m.sees(cx.w, Who::Mob(*i)))
.collect();
let Some(&(target, partner_willing)) = visible.first() else {
return false;
};
// RunOne weights: interact 2, breed 1 (when both are willing).
let breed = breedable && partner_willing && m.random.next_int_bound(3).unwrap_or(0) == 0;
self.target = Some(target);
self.breed = breed;
true
}
}
impl Goal for Social {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if m.is_baby() || sleeping(m) || raid_status(m) != RAID_NONE {
return false;
}
if self.cooldown > 0 {
self.cooldown -= 1;
return false;
}
match activity(m, cx.w.day_time) {
Activity::Idle => self.pick(m, cx),
Activity::Meet => {
// SocializeAtBell: one tick in a hundred, near the bell.
let near_bell = m.extra.meeting.is_some_and(|p| distance(m, p) < 4.0);
near_bell && m.random.next_int_bound(100).unwrap_or(1) == 0 && {
let ok = self.pick(m, cx);
self.breed = false;
ok
}
}
_ => false,
}
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(t) = self.target else { return false };
let Some(s) = cx.w.seen(t) else { return false };
if !s.alive || sleeping(m) || raid_status(m) != RAID_NONE {
return false;
}
if self.breed {
self.ticks < 350 && can_breed(m) && s.in_love
} else {
self.ticks < 60
}
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
self.ticks = 0;
self.birth_at = 0;
if let Some(s) = self.target.and_then(|t| cx.w.seen(t)) {
let at = [s.position.x, s.position.y, s.position.z];
m.nav_move_to(cx.w, at, 0.5);
}
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
m.nav_stop();
self.target = None;
self.cooldown = 20 + m.random.next_int_bound(40).unwrap_or(0);
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
self.ticks += 1;
let Some(t) = self.target else { return };
let Some(s) = cx.w.seen(t) else { return };
let (at, eye) = ([s.position.x, s.position.y, s.position.z], s.eye_y);
m.look_at([at[0], eye, at[2]]);
if m.position.distance_squared(s.position) > 5.0 {
if m.ai.nav.is_done() && self.ticks % 10 == 1 {
m.nav_move_to(cx.w, at, 0.5);
}
return;
}
m.nav_stop();
if !self.breed {
cx.events.push(MobEvent::VillagerMeet {
mob: m.id,
other: t,
});
return;
}
let now = cx.w.game_time;
if self.birth_at == 0 {
self.birth_at = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0));
}
if now >= self.birth_at {
cx.events.push(MobEvent::VillagerBirth {
parent: m.id,
partner: t,
});
self.ticks = 1000;
} else if m.random.next_int_bound(35).unwrap_or(1) == 0 {
for p in [m.position, s.position] {
cx.events.push(MobEvent::Particles {
kind: "heart",
at: [p.x, p.y + 1.8, p.z],
count: 1,
});
}
}
}
}
/// `VillagerPanicTrigger.tick`: a frightened villager calls for a golem
/// every five seconds.
#[derive(Clone, Debug, Default)]
struct GolemCall;
/// `VillagerHostilesSensor`: how close each hostile must be to scare.
fn hostile_range(s: Species) -> f64 {
match s {
Species::Drowned
| Species::Husk
| Species::Vex
| Species::Zombie
| Species::ZombieVillager => 8.0,
Species::Evoker | Species::Ravager => 12.0,
Species::Pillager => 15.0,
Species::Vindicator | Species::Zoglin => 10.0,
_ => 0.0,
}
}
fn frightened(m: &Mob, cx: &Cx) -> bool {
// HURT_BY lasts 100 ticks.
let hurt = m.ai.last_hurt_by.is_some() && m.age as i32 - m.ai.last_hurt_by_time <= 100;
hurt || cx.w.others.iter().any(|s| {
s.alive && {
let r = hostile_range(s.species);
r > 0.0 && s.position.distance_squared(m.position) <= r * r
}
})
}
impl Goal for GolemCall {
goal_clone!();
fn flags(&self) -> u8 {
0
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
!m.is_baby() && frightened(m, cx)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.can_use(m, cx)
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
if cx.w.game_time % 100 == 0 {
cx.events.push(MobEvent::GolemCheck {
mob: m.id,
needed: 3,
});
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn stack(item: &str, count: u32) -> ItemStack {
ItemStack::new(item, count)
}
#[test]
fn eating_fills_the_food_level_then_digests() {
let mut e = Ext {
inventory: vec![stack("minecraft:bread", 3), stack("minecraft:carrot", 5)],
..Default::default()
};
assert_eq!(e.food_in_inventory(), 17);
// Hungry below 12: three breads fill it exactly, then 12 digest away.
e.eat_and_digest();
assert_eq!(e.food_level, 0);
assert_eq!(e.inventory.len(), 1);
assert_eq!(e.inventory[0].count, 5);
// Five carrots are not enough to be full again, and are all eaten.
e.eat_and_digest();
assert_eq!(e.food_level, 5 - 12);
assert!(e.inventory.is_empty());
}
#[test]
fn willingness_to_breed_needs_twelve_food_points() {
let mut e = Ext::default();
assert!(e.wants_more_food() && !e.has_excess_food());
e.inventory.push(stack("minecraft:bread", 6));
assert!(e.has_excess_food() && !e.wants_more_food());
e.food_level = -5;
assert_eq!(e.food_level + e.food_in_inventory(), 19);
}
#[test]
fn the_inventory_has_eight_stacking_slots() {
let mut e = Ext::default();
assert!(e.add_item(stack("minecraft:bread", 100), 64).is_none());
assert_eq!(e.inventory.len(), 2);
assert_eq!(e.inventory[0].count, 64);
for i in 0..6 {
assert!(
e.add_item(stack(&format!("minecraft:item_{i}"), 1), 64)
.is_none()
);
}
assert_eq!(e.inventory.len(), 8);
// Full: another kind is refused, the same kind tops up the stack.
assert!(!e.can_add(&stack("minecraft:stick", 1), 64));
let left = e.add_item(stack("minecraft:bread", 40), 64).unwrap();
assert_eq!(left.count, 40 - 28);
}
#[test]
fn half_stacks_are_thrown() {
let mut e = Ext {
inventory: vec![
stack("minecraft:bread", 10),
stack("minecraft:wheat", 50),
stack("minecraft:wheat", 20),
],
..Default::default()
};
let max = |_: &str| 64;
// Bread is under half a stack and under 24: nothing.
assert!(
e.take_half_stack(|s| &*s.item == "minecraft:bread", max)
.is_none()
);
// 50 wheat is over half a stack: 25 go.
let t = e
.take_half_stack(|s| &*s.item == "minecraft:wheat", max)
.unwrap();
assert_eq!(t.count, 25);
assert_eq!(e.count_item("minecraft:wheat"), 25 + 20);
}
#[test]
fn golems_need_sleep_and_no_golem_nearby() {
let mut e = Ext::default();
assert!(!e.wants_golem(100));
e.last_slept = Some(0);
assert!(e.wants_golem(23_999));
assert!(!e.wants_golem(24_000));
e.last_slept = Some(1000);
e.golem_until = 2000 + 599;
assert!(!e.wants_golem(2500));
assert!(e.wants_golem(2700));
}
#[test]
fn gossip_decays_once_a_day_and_heard_gossip_waits() {
let player = [1, 2, 3, 4];
let mut e = Ext::default();
e.gossips
.add(player, crate::gossip::GossipType::MajorNegative, 25);
e.maybe_decay(100);
assert_eq!(e.last_gossip_decay, 100);
e.maybe_decay(24_099);
assert_eq!(
e.gossips
.get(player, crate::gossip::GossipType::MajorNegative),
25
);
e.maybe_decay(24_100);
assert_eq!(
e.gossips
.get(player, crate::gossip::GossipType::MajorNegative),
15
);
e.last_gossip_time = 5000;
assert!(!e.can_gossip(5100));
assert!(e.can_gossip(6200));
assert!(e.can_gossip(4000));
}
#[test]
fn villager_food_values() {
assert_eq!(food_points("minecraft:bread"), 4);
assert_eq!(food_points("minecraft:beetroot"), 1);
assert_eq!(food_points("minecraft:apple"), 0);
}
}
+12 -5
View File
@@ -59,11 +59,18 @@ pub fn block_entities(
.iter_mut()
.zip(loot.fill(&table, seed, 27, Some(biome)))
{
*slot = stack.map(|s| ItemStack {
item: Arc::from(s.item.as_str()),
count: s.count.max(0) as u32,
damage: s.damage.max(0) as u32,
extra: None,
*slot = stack.map(|s| {
let mut item = ItemStack {
item: Arc::from(s.item.as_str()),
count: s.count.max(0) as u32,
damage: s.damage.max(0) as u32,
extra: None,
};
// An ominous bottle's level (the default, 0, is no component).
if let Some(level) = s.ominous_amplifier.filter(|l| *l > 0) {
item.data_mut().ominous_amplifier = Some(level.clamp(0, 4) as u8);
}
item
});
}
}
+4 -1
View File
@@ -23,6 +23,8 @@ pub struct LootStack {
pub potion: Option<String>,
/// Set by exploration_map (the map_id component of a found map).
pub map: bool,
/// Set by set_ominous_bottle_amplifier.
pub ominous_amplifier: Option<i32>,
}
impl LootStack {
fn new(item: &str) -> Self {
@@ -33,6 +35,7 @@ impl LootStack {
enchantments: Vec::new(),
potion: None,
map: false,
ominous_amplifier: None,
}
}
pub fn is_empty(&self) -> bool {
@@ -584,7 +587,7 @@ impl Context<'_> {
}
}
"minecraft:set_ominous_bottle_amplifier" => {
self.int(&f["amplifier"]);
stack.ominous_amplifier = Some(self.int(&f["amplifier"]));
}
"minecraft:set_instrument" => {
let options = data.holder_set("instrument", &f["options"]);