diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index d773a509b..417e28c0f 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -293,6 +293,47 @@ fn spawn_seed(index: usize) -> i64 { 1000 + 7919 * index as i64 } +/// `Villager.spawnGolemIfNeeded` for villager `a`, the game's way: the golem +/// draws from the level's random and joins the scenario's mobs next tick, +/// seeded as the oracle seeds what a tick spawned. +fn summon_golem( + mobs: &mut [Mob], + a: usize, + needed: usize, + w: &MobWorld, + types: &MobTypes, + born: &mut Vec, + level_random: &mut LegacyRandom, +) { + use horizon_client::mobs::{villager, villager_brain}; + let Some(near) = villager::golem_summoners(mobs, a, w.game_time, needed) else { + return; + }; + let kind = Arc::new( + types + .types + .get("minecraft:iron_golem") + .expect("iron golem") + .clone(), + ); + let index = mobs.len() + born.len(); + let p = mobs[a].position; + let start = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; + let golem = villager::summon_golem(w, start, level_random, |random, at, yaw| { + let mut m = Mob::new(100_000 + index as u32, kind.clone(), at, yaw); + villager::finalize_summoned_golem(&mut m, random); + m + }); + let Some(mut golem) = golem else { + return; + }; + golem.random = LegacyRandom::new(spawn_seed(index)); + born.push(golem); + for j in near { + villager_brain::golem_detected(&mut mobs[j], w.game_time); + } +} + /// Villager events that act at once in vanilla (`TradeWithVillager` and /// `VillagerMakeLove` write the other villager directly). fn villager_events( @@ -304,6 +345,7 @@ fn villager_events( items: &Items, born: &mut Vec, day_time: i64, + level_random: &mut LegacyRandom, ) { use horizon_client::mobs::villager; let index = |mobs: &[Mob], id: u32| { @@ -314,6 +356,7 @@ fn villager_events( while i < events.len() { match events[i] { MobEvent::VillagerMeet { mob, other } => { + events.remove(i); if let (Some(a), Some(b)) = (index(mobs, mob), index(mobs, other)) { let meeting = villager::meet(mobs, a, b, w.game_time, |item| { items.get(item).map_or(64, |i| i.max_stack) @@ -322,8 +365,16 @@ fn villager_events( meeting.thrown.is_empty(), "villagers toss items: not modelled here" ); + if meeting.gossiped { + summon_golem(mobs, a, 5, w, types, born, level_random); + } } + } + MobEvent::GolemCheck { mob, needed } => { events.remove(i); + if let Some(a) = index(mobs, mob) { + summon_golem(mobs, a, needed, w, types, born, level_random); + } } MobEvent::VillagerBirth { parent, @@ -1167,6 +1218,7 @@ pub fn main() -> horizon_client::Result<()> { &items, &mut born, s.time, + &mut scratch, ); horizon_client::mobs::warden::hear_mob_events(&mut mobs, &events, from, &w); // Melee hits on other mobs land during the attacker's tick diff --git a/crates/horizon-client/src/game/villagers.rs b/crates/horizon-client/src/game/villagers.rs index 5c6bed394..3cfe8aa1d 100644 --- a/crates/horizon-client/src/game/villagers.rs +++ b/crates/horizon-client/src/game/villagers.rs @@ -5,34 +5,13 @@ use super::Game; use horizon_client::{ gossip::{self, GossipType}, items::ItemStack, - mobs::{Mob, Species, spawning, villager}, + mobs::{Mob, Species, spawning, villager, villager_brain}, }; -use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_core::geometry::Vec3; 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 { self.mobs @@ -76,88 +55,46 @@ impl Game<'_> { return; }; let now = self.world.game_time; - if !villager::ext(&self.mobs[i]).is_some_and(|e| e.wants_golem(now)) { + let Some(near) = villager::golem_summoners(&self.mobs, i, now, needed) else { return; - } - let at = self.mobs[i].position; - let nearby: Vec = 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; + }; + if self.try_spawn_iron_golem(block_of(self.mobs[i].position)) { + for j in near { + villager_brain::golem_detected(&mut self.mobs[j], now); } } } - /// `SpawnUtil.trySpawnMob(IRON_GOLEM, ..., 10 attempts, 8 across, 6 up - /// and down, LEGACY_IRON_GOLEM)`. + /// `SpawnUtil.trySpawnMob(IRON_GOLEM, ...)`: a golem near `start`, with + /// the ambient sound `trySpawnMob` plays. 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; - } + let Some(kind) = self.res.mob_types().get("minecraft:iron_golem").cloned() else { + return false; + }; + let id = self.next_entity + 1; + let mut random = self.world.random.clone(); + let golem = villager::summon_golem( + &self.mob_world_base(&[]), + start, + &mut random, + |random, at, yaw| { + let mut m = Mob::new(id, kind.clone(), at, yaw); + villager::finalize_summoned_golem(&mut m, random); + m + }, + ); + self.world.random = random; + let Some(golem) = golem else { + return false; + }; + self.next_entity = id; + let sound = golem.kind.sounds[0]; + if !sound.is_empty() { + let at = golem.center(); + self.audio + .play(&format!("minecraft:{sound}"), Some(at), 1.0, 1.0); } - false + self.mobs.push(golem); + true } /// `VillagerMakeLove.tryToGiveBirth`: both eat, a free bed within 48 diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index b5abad9f0..575fafaed 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -614,6 +614,144 @@ pub fn meet( gossiped: ready, } } +/// `Villager.spawnGolemIfNeeded` up to the spawn: villager `i` wants a golem +/// and so do at least `needed` of the villagers whose boxes meet its own grown +/// by 10 blocks. Returns all of those villagers: once the golem stands, they +/// remember it ([`super::villager_brain::golem_detected`]). +pub fn golem_summoners(mobs: &[Mob], i: usize, now: i64, needed: usize) -> Option> { + if !ext(&mobs[i]).is_some_and(|e| e.wants_golem(now)) { + return None; + } + let area = mobs[i] + .bounds() + .inflate(horizon_core::geometry::Vec3::new(10.0, 10.0, 10.0)); + let near: Vec = mobs + .iter() + .enumerate() + .filter(|(_, m)| { + m.species() == Species::Villager && !m.removed && m.bounds().intersects(area) + }) + .map(|(j, _)| j) + .collect(); + let wanting = near + .iter() + .filter(|&&j| ext(&mobs[j]).is_some_and(|e| e.wants_golem(now))) + .take(5) + .count(); + (wanting >= needed).then_some(near) +} +/// `SpawnUtil.Strategy.LEGACY_IRON_GOLEM`'s refused floors. +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") +} +/// One attempt of `SpawnUtil.trySpawnMob(IRON_GOLEM, ..., 8 across, 6 up and +/// down, LEGACY_IRON_GOLEM)`: a column drawn near `start`, searched down from +/// 6 above for a solid floor (or powder snow) under air or a liquid block. +/// Returns the block the golem would stand in. +fn golem_attempt( + l: &L, + start: [i32; 3], + random: &mut impl RandomSource, +) -> Option<[i32; 3]> { + let dx = random.next_int_bound(17).unwrap_or(8) - 8; + let dz = random.next_int_bound(17).unwrap_or(8) - 8; + let (x, z) = (start[0] + dx, start[2] + dz); + let name = |y: i32| -> &str { &l.facts().get(l.state(x, y, z)).name }; + let mut y = start[1] + 6; + let mut above = l.state(x, y, z); + for _ in 0..=12 { + y -= 1; + let here = l.state(x, y, z); + let above_name = &*l.facts().get(above).name; + // BlockState.liquid(): a water or lava block (not a waterlogged one). + let open = l.facts().is_air(above) + || above_name == "minecraft:water" + || above_name == "minecraft:lava"; + let solid = l.mob_data().state(here).flags & super::data::SOLID != 0 + || name(y) == "minecraft:powder_snow"; + if golem_floor_ok(name(y)) && open && solid { + return Some([x, y + 1, z]); + } + above = here; + } + None +} +/// `IronGolem.checkSpawnObstruction`: a floor with a full top face, its feet +/// free whatever fluid is there, and the two blocks above free. +fn golem_fits(l: &L, [x, y, z]: [i32; 3]) -> bool { + use super::spawn_rules::is_valid_empty_spawn; + // entityCanStandOn: Block.isFaceFull(collision shape, UP). + let floor = l.mob_data().state(l.state(x, y - 1, z)); + let stands = floor.flags & super::data::STURDY_TOP != 0 && floor.top >= 1.0; + // isValidEmptySpawnBlock with Fluids.EMPTY: open water is free too. + let feet = is_valid_empty_spawn(Species::IronGolem, l, x, y, z) + || &*l.facts().get(l.state(x, y, z)).name == "minecraft:water"; + stands + && feet + && is_valid_empty_spawn(Species::IronGolem, l, x, y + 1, z) + && is_valid_empty_spawn(Species::IronGolem, l, x, y + 2, z) +} +/// `SpawnUtil.trySpawnMob(IRON_GOLEM, MOB_SUMMONED, level, start, 10, 8, 6, +/// LEGACY_IRON_GOLEM, false)`: up to ten columns tried. In each spot found +/// `create` makes the golem (`EntityType.create`: the yaw drawn here, then its +/// `finalizeSpawn` draws, see [`finalize_summoned_golem`]); it is kept only +/// when `IronGolem.checkSpawnObstruction` passes, and discarded otherwise. +pub fn summon_golem( + l: &L, + start: [i32; 3], + random: &mut R, + mut create: impl FnMut(&mut R, horizon_core::geometry::Vec3, f32) -> T, +) -> Option { + for _ in 0..10 { + let Some([x, y, z]) = golem_attempt(l, start, random) else { + continue; + }; + // Mth.wrapDegrees(nextFloat() * 360). + let mut yaw = random.next_float() * 360.0; + if yaw >= 180.0 { + yaw -= 360.0; + } + let at = + horizon_core::geometry::Vec3::new(f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5); + let golem = create(random, at, yaw); + if golem_fits(l, [x, y, z]) { + return Some(golem); + } + } + None +} +/// `Mob.finalizeSpawn` for a summoned iron golem, from the level's random: +/// the follow range spawn bonus and left-handedness. +pub fn finalize_summoned_golem(m: &mut Mob, random: &mut impl RandomSource) { + use super::finalize::{Attr, Op, add_modifier, has_modifier}; + if !has_modifier(m, Attr::FollowRange, "minecraft:random_spawn_bonus") { + let bonus = random.triangle(0.0, 0.114_850_000_000_000_01); + add_modifier( + m, + Attr::FollowRange, + "minecraft:random_spawn_bonus", + bonus, + Op::AddMultipliedBase, + ); + } + m.extra.left_handed = random.next_float() < 0.05; +} /// `PoiManager.take(HOME, ..., 48)`: the nearest bed head not `claimed` /// (`free_head`: a bed head that is not occupied). pub fn take_vacant_bed( diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index df19d8fed..336dc6b93 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -779,6 +779,14 @@ fn sense_golem(m: &mut Mob, w: &MobWorld) { } } +/// `GolemSensor.golemDetected`: a golem was summoned near this villager; +/// for 599 ticks it wants no other. +pub fn golem_detected(m: &mut Mob, now: i64) { + mem(m).golem_detected_recently.set_ttl(true, 599); + // What `sync` derives from the memory. + super::villager::ext_mut(m).golem_until = now + 599 + 1; +} + // ---- Behaviours --------------------------------------------------------- /// The POI types villagers use. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java index 55c0370f4..5808fec0d 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -761,12 +761,14 @@ public final class VanillaMobAiOracle { level.tickBlockEntities(); } else if (!heartPositions.isEmpty()) level.tickBlockEntities(); managerTick.invoke(manager); - // Villagers the tick spawned (babies) and a heart's creakings tick from the next - // one, in the order they were added, with a seeded random of their own. Other - // newcomers (animal babies, dropped items) are left out, as the probe leaves them. + // Villagers the tick spawned (babies), the iron golems they summoned and a heart's + // creakings tick from the next one, in the order they were added, with a seeded + // random of their own. Other newcomers (animal babies, dropped items) are left out, + // as the probe leaves them. List fresh = new ArrayList<>(); for (Entity e : level.getAllEntities()) - if (!LABELS.containsKey(e) && (e instanceof Villager || e instanceof net.minecraft.world.entity.animal.bee.Bee || created.contains(e))) fresh.add(e); + if (!LABELS.containsKey(e) && (e instanceof Villager || e instanceof net.minecraft.world.entity.animal.bee.Bee + || e instanceof net.minecraft.world.entity.animal.golem.IronGolem || created.contains(e))) fresh.add(e); fresh.sort(java.util.Comparator.comparingInt(Entity::getId)); for (Entity e : fresh) { int index = ENTS.size(); diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index ccc50b302..338c97e53 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -285,6 +285,22 @@ def scenarios(): 'block 0 -60 0 minecraft:composter', 'mob minecraft:villager 10.5 -60 0.5 90 54 persistent', ]) + # Villagers that slept today and saw no golem summon an iron golem (Villager.spawnGolemIfNeeded): + # five gossiping (TradeWithVillager, at tick 200 here), or three panicking at a zombie in a pen + # (VillagerPanicTrigger, at tick 100 by night). They all remember it (GOLEM_DETECTED_RECENTLY). + # Under a glass roof three blocks up the golem still fits (IronGolem.checkSpawnObstruction); + # on dirt paths it cannot stand. The scenarios stop on the summoning tick: the golem's own AI + # (MoveBackToVillageGoal, GolemRandomStrollInVillageGoal) is not ported yet. + golem_callers = [f'mob minecraft:villager {x} -60 {z} {r} {seed} persistent slept=1' for x, z, r, seed in + [(0.5, 0.5, 0, 81), (2.5, 0.5, 180, 82), (0.5, 2.5, 90, 83), (2.5, 2.5, 270, 84), (1.5, -1.5, 0, 85)]] + add('villager_golem_gossip', 200, ['player 14.5 -60 0.5'] + golem_callers, 'time=100') + add('villager_golem_roof', 200, ['fill -10 -57 -12 13 -57 13 minecraft:glass', 'player 14.5 -60 0.5'] + golem_callers, + 'time=100') + add('villager_golem_paths', 400, ['fill -10 -61 -12 13 -61 13 minecraft:dirt_path', 'player 14.5 -60 0.5'] + golem_callers, + 'time=100') + add('villager_golem_panic', 100, ['fill -2 -60 -3 4 -60 4 minecraft:oak_fence', 'fill -1 -60 -2 3 -60 3 minecraft:air', + 'player 14.5 -60 0.5'] + golem_callers[:3] + + ['mob minecraft:zombie 6.5 -60 0.5 90 86 persistent noai'], 'time=18000') return s