From 5ea641a7c2a86eb7882873660b0c8be3a384be96 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 17:46:50 +0200 Subject: [PATCH 1/5] WIP: unfinished villager-social parity work, stopped by Ludovic Uncommitted changes the agent had in progress when it was stopped on 2026-10-12; may not build or pass its harnesses yet. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs.rs | 89 +++++-- crates/horizon-client/src/mobs/villager.rs | 40 ++++ .../horizon-client/src/mobs/villager_brain.rs | 59 +++++ .../horizonlab/parity/VanillaMobAiOracle.java | 220 ++++++++++++++++-- tools/test_mob_ai_parity.py | 21 +- 5 files changed, 385 insertions(+), 44 deletions(-) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 5200e465b..a0fd95479 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -761,20 +761,11 @@ 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, + /// What a villager's tick does to another villager at once + /// (`take_mob_ops` applies it before the next mob ticks). + VillagerOp { + target: u32, + op: villager_brain::Op, }, /// A villager launches a firework rocket (celebrating a won raid). Firework { @@ -903,8 +894,57 @@ pub struct Seen { /// A villager's profession (index into `render::PROFESSIONS`) and experience. pub profession: u8, pub xp: i32, + /// What other villagers read of a villager's state and brain. + pub villager: Option>, } impl Mob { + /// What other mobs see of this one this tick (`player`: the player's + /// UUID, which villagers' reputation is keyed by). + pub fn seen(&self, player: Option<[i32; 4]>) -> Seen { + let m = self; + let villager = m.species() == Species::Villager; + Seen { + id: m.id, + species: m.species(), + position: m.position, + bounds: m.bounds(), + eye_y: m.eye_y(), + alive: m.alive(), + baby: m.is_baby(), + // A villager is "in love" when it is willing to breed (`canBreed`). + in_love: if villager { + villager::can_breed(m) + } else { + m.extra.in_love > 0 + }, + tame: m.extra.tame, + hostile: m.hostile(), + target: m.ai.target, + health: m.health, + variant: m.extra.variant, + color: m.extra.color, + job: villager.then_some(m.extra.home).flatten(), + bed: villager.then_some(m.extra.bed).flatten(), + yaw: m.yaw, + velocity: m.velocity, + leash: m.extra.leash, + caravan: caravan::head_of(m), + delay: m.extra.ints[5], + hurt_by: m.ai.last_hurt_by.map(|w| (w, m.ai.last_hurt_by_time)), + active_raid: raider::has_active_raid(m), + player_rep: match (villager, player) { + (true, Some(uuid)) => villager::ext(m).map_or(0, |e| e.gossips.reputation(uuid)), + _ => 0, + }, + pushable: m.pushable(), + category: m.category(), + potential_job: villager_brain::potential_job_site(m), + meeting: villager.then_some(m.extra.meeting).flatten(), + profession: m.extra.variant2, + xp: villager::xp(m), + villager: villager.then(|| Arc::new(villager::seen(m))), + } + } /// `EntityType.getCategory`'s name. pub fn category(&self) -> &'static str { match self.kind.category.as_str() { @@ -938,6 +978,27 @@ pub fn take_mob_pushes(events: &mut Vec, from: usize, pending: &mut Ve } } } +/// Applies the `VillagerOp`s in `events[from..]` to the mobs they target, +/// at once, as vanilla's villagers write each other directly. Returns the +/// indices of the mobs changed (whose snapshot is stale). +pub fn take_mob_ops(mobs: &mut [Mob], events: &mut Vec, from: usize) -> Vec { + let mut changed = Vec::new(); + let mut i = from; + while i < events.len() { + if let MobEvent::VillagerOp { target, op } = &events[i] { + if let Some(j) = mobs.iter().position(|m| m.id == *target && !m.removed) { + villager_brain::apply_op(&mut mobs[j], op); + if !changed.contains(&j) { + changed.push(j); + } + } + events.remove(i); + } else { + i += 1; + } + } + changed +} /// Adds the pending pushes aimed at `m` to its velocity, in push order. pub fn apply_mob_pushes(m: &mut Mob, pending: &mut Vec<(u32, Vec3)>) { pending.retain(|(id, v)| { diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index 447a80072..eef96fd53 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -488,6 +488,46 @@ impl Ext { now < self.last_gossip_time || now >= self.last_gossip_time + 1200 } } +/// What a villager ticking later reads of another one this tick (vanilla +/// reads the other villager itself). +#[derive(Clone, Debug, Default)] +pub struct Seen { + pub gossips: crate::gossip::Gossips, + pub last_gossip_time: i64, + /// `countFoodPointsInInventory`. + pub food_points: i32, + /// The `INTERACTION_TARGET` memory (play tag's chases). + pub interaction_target: Option, + /// The `PATH` memory, when not done: its previous and next nodes. + pub path_nodes: Option<(Option<[i32; 3]>, [i32; 3])>, + /// `LAST_SLEPT` and whether `GOLEM_DETECTED_RECENTLY` is remembered. + pub last_slept: Option, + pub golem_detected: bool, +} +impl Seen { + /// `Villager.wantsToSpawnGolem`. + pub fn wants_golem(&self, now: i64) -> bool { + self.last_slept.is_some_and(|t| now - t < 24000) && !self.golem_detected + } + /// `Villager.wantsMoreFood`. + pub fn wants_more_food(&self) -> bool { + self.food_points < 12 + } +} +pub fn seen(m: &Mob) -> Seen { + let e = ext(m); + let (interaction_target, path_nodes, golem_detected, last_slept) = + super::villager_brain::seen_memories(m); + Seen { + gossips: e.map(|e| e.gossips.clone()).unwrap_or_default(), + last_gossip_time: e.map_or(0, |e| e.last_gossip_time), + food_points: e.map_or(0, Ext::food_in_inventory), + interaction_target, + path_nodes, + last_slept: last_slept.or(e.and_then(|e| e.last_slept)), + golem_detected, + } +} /// `Villager.canBreed`: enough food, awake and an adult. pub fn can_breed(m: &Mob) -> bool { m.species() == Species::Villager diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index beb877bb1..3272a6ab0 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -4076,3 +4076,62 @@ pub fn potential_job_site(m: &Mob) -> Option<[i32; 3]> { pub fn seen_can_breed(s: &Seen) -> bool { s.species == Species::Villager && s.in_love } +/// The memories other villagers read: the interaction target, the path's +/// nodes (while it is not done), whether a golem was seen lately and the +/// last sleep. +#[allow(clippy::type_complexity)] +pub fn seen_memories( + m: &Mob, +) -> ( + Option, + Option<(Option<[i32; 3]>, [i32; 3])>, + bool, + Option, +) { + let Some(mm) = mem_ref(m) else { + return (None, None, false, None); + }; + let path = mm.path.present().then(|| m.ai.nav.path.as_ref()).flatten(); + let nodes = path.filter(|p| !p.is_done()).map(|p| { + let n = |i: usize| [p.nodes[i].x, p.nodes[i].y, p.nodes[i].z]; + ((p.next > 0).then(|| n(p.next - 1)), n(p.next)) + }); + ( + mm.interaction_target.value(), + nodes, + mm.golem_detected_recently.present(), + mm.last_slept.value(), + ) +} +/// What one villager's tick does to another at once (vanilla writes the +/// other villager directly): applied before the next mob ticks. +#[derive(Clone, Debug)] +pub enum Op { + /// `BehaviorUtils.lockGazeAndWalkToEachOther`, the other villager's half. + LockGaze(Who), + /// `Villager.gossip`: the target's `lastGossipTime`. + GossipTime(i64), + /// `Villager.eatAndDigestFood`. + EatAndDigest, + /// `AgeableMob.setAge`. + SetAge(i32), + /// `GolemSensor.golemDetected`. + GolemDetected, +} +/// Applies an `Op` to the villager it targets. +pub fn apply_op(m: &mut Mob, op: &Op) { + if m.species() != Species::Villager { + return; + } + match op { + Op::LockGaze(who) => lock_gaze(m, *who), + Op::GossipTime(t) => super::villager::ext_mut(m).last_gossip_time = *t, + Op::EatAndDigest => super::villager::ext_mut(m).eat_and_digest(), + Op::SetAge(age) => m.extra.age = *age, + Op::GolemDetected => golem_detected(m), + } +} +/// `GolemSensor.golemDetected`: remembered for 600 ticks. +fn golem_detected(m: &mut Mob) { + mem(m).golem_detected_recently.set_ttl(true, 600); +} 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 7185ec400..ad63af6cf 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -65,6 +65,8 @@ import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.AgeableMob; +import net.minecraft.world.entity.item.ItemEntity; +import net.minecraft.world.entity.npc.villager.Villager; import net.minecraft.world.entity.ai.Brain; import net.minecraft.world.entity.ai.behavior.BehaviorControl; import net.minecraft.world.entity.ai.behavior.BlockPosTracker; @@ -138,6 +140,10 @@ public final class VanillaMobAiOracle { } } static final List TRACE = new ArrayList<>(); + /** The entities a scenario ticks, in order: its mobs, then what they spawned. */ + static final List ENTS = new ArrayList<>(); + static final Map LABELS = new java.util.IdentityHashMap<>(); + static final UUID PLAYER_UUID = new UUID(0x1234L, 0x5678L); static final class MobSpec { String type; @@ -159,6 +165,12 @@ public final class VanillaMobAiOracle { boolean creative; List mobs = new ArrayList<>(); long levelSeed = 0; + /** The day time advances with the game time (sleeping, waking). */ + boolean daycycle; + /** Blocks changed before a given tick: (tick, block or fill line). */ + List timed = new ArrayList<>(); + /** Boxes whose block changes are printed every tick. */ + List watches = new ArrayList<>(); } static void parse(Path path) throws Exception { @@ -179,12 +191,19 @@ public final class VanillaMobAiOracle { case "rain" -> s.rain = true; case "thunder" -> s.thunder = true; case "levelseed" -> s.levelSeed = Long.parseLong(kv[1]); + case "daycycle" -> s.daycycle = true; default -> throw new IllegalArgumentException(line); } } } case "origin" -> { s.originX = Integer.parseInt(f[1]); s.originZ = Integer.parseInt(f[2]); } case "fill", "block" -> s.blocks.add(f); + case "at" -> s.timed.add(new Object[] {Integer.parseInt(f[1]), java.util.Arrays.copyOfRange(f, 2, f.length)}); + case "watch" -> { + int[] box = new int[6]; + for (int i = 0; i < 6; i++) box[i] = Integer.parseInt(f[i + 1]); + s.watches.add(box); + } case "player" -> { s.player = new double[] {Double.parseDouble(f[1]), Double.parseDouble(f[2]), Double.parseDouble(f[3])}; s.creative = f.length > 4 && f[4].equals("creative"); @@ -401,8 +420,12 @@ public final class VanillaMobAiOracle { } void build(Scenario s, ServerLevel level) throws Exception { + for (String[] b : s.blocks) place(b, level); + } + + static void place(String[] b, ServerLevel level) throws Exception { var blocks = level.holderLookup(Registries.BLOCK); - for (String[] b : s.blocks) { + { if (b[0].equals("block")) { BlockState state = BlockStateParser.parseForBlock(blocks, b[4], false).blockState(); level.setBlock(new BlockPos(Integer.parseInt(b[1]), Integer.parseInt(b[2]), Integer.parseInt(b[3])), state, 2 | 16); @@ -429,7 +452,7 @@ public final class VanillaMobAiOracle { level.setThunderLevel(s.thunder ? 1.0F : 0.0F); if (s.player != null) { if (player == null) { - CommonListenerCookie cookie = CommonListenerCookie.createInitial(new GameProfile(new UUID(0x1234L, 0x5678L), "horizon-ai"), false); + CommonListenerCookie cookie = CommonListenerCookie.createInitial(new GameProfile(PLAYER_UUID, "horizon-ai"), false); player = new ServerPlayer(this, level, cookie.gameProfile(), cookie.clientInformation()); Connection connection = new Connection(PacketFlow.SERVERBOUND); new EmbeddedChannel(connection); @@ -448,14 +471,15 @@ public final class VanillaMobAiOracle { } else if (player != null) { player.snapTo(s.originX + 5000, -60, s.originZ, 0.0F, 0.0F); } - List mobs = new ArrayList<>(); + ENTS.clear(); + LABELS.clear(); List> brains = new ArrayList<>(); List seeds = new ArrayList<>(); int id = 100000; for (MobSpec spec : s.mobs) { EntityType type = BuiltInRegistries.ENTITY_TYPE.getValue(net.minecraft.resources.Identifier.parse(spec.type)); Mob mob = (Mob) type.create(level, EntitySpawnReason.COMMAND); - if (tracing(s)) field(Entity.class, "random").set(mob, new TracingRandom(0L, TRACE, mobs.size())); + if (tracing(s)) field(Entity.class, "random").set(mob, new TracingRandom(0L, TRACE, ENTS.size())); mob.setId(id++); mob.snapTo(spec.x, spec.y, spec.z, spec.yaw, 0.0F); mob.setYHeadRot(spec.yaw); @@ -464,29 +488,80 @@ public final class VanillaMobAiOracle { if (mob instanceof AgeableMob a) a.setBaby(true); else mob.setBaby(true); } + List afterAdd = new ArrayList<>(); for (String flag : spec.flags) { - if (flag.equals("persistent")) mob.setPersistenceRequired(); - else if (flag.equals("noai")) mob.setNoAi(true); - else throw new IllegalArgumentException(flag); + String[] kv = flag.split("=", 2); + String v = kv.length > 1 ? kv[1] : ""; + switch (kv[0]) { + case "persistent" -> mob.setPersistenceRequired(); + case "noai" -> mob.setNoAi(true); + case "profession" -> { + Villager villager = (Villager) mob; + villager.setVillagerData(villager.getVillagerData().withProfession(level.registryAccess(), + ResourceKey.create(Registries.VILLAGER_PROFESSION, net.minecraft.resources.Identifier.withDefaultNamespace(v)))); + villager.refreshBrain(level); + } + case "level" -> { + Villager villager = (Villager) mob; + villager.setVillagerData(villager.getVillagerData().withLevel(Integer.parseInt(v))); + } + case "xp" -> ((Villager) mob).setVillagerXp(Integer.parseInt(v)); + case "food" -> field(Villager.class, "foodLevel").setInt(mob, Integer.parseInt(v)); + case "age" -> ((AgeableMob) mob).setAge(Integer.parseInt(v)); + case "inv" -> { + for (String item : v.split(",")) { + String[] ic = item.split("\\*"); + ((Villager) mob).getInventory().addItem(new net.minecraft.world.item.ItemStack( + BuiltInRegistries.ITEM.getValue(net.minecraft.resources.Identifier.parse(ic[0])), + ic.length > 1 ? Integer.parseInt(ic[1]) : 1)); + } + } + case "gossip" -> { + // gossip=player:minor_negative:100 + String[] g = v.split(":"); + UUID target = g[0].equals("player") ? PLAYER_UUID : UUID.fromString(g[0]); + ((Villager) mob).getGossips().add(target, + net.minecraft.world.entity.ai.gossip.GossipType.valueOf(g[1].toUpperCase(java.util.Locale.ROOT)), Integer.parseInt(g[2])); + } + case "slept" -> { + long at = Long.parseLong(v); + afterAdd.add(() -> mob.getBrain().setMemory(MemoryModuleType.LAST_SLEPT, at)); + } + default -> throw new IllegalArgumentException(flag); + } } level.addFreshEntity(mob); + for (Runnable r : afterAdd) r.run(); mob.getRandom().setSeed(spec.seed); Brain brain = mob.getBrain(); @SuppressWarnings("unchecked") Map> sensors = (Map>) get(brain, "sensors"); for (Sensor sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom()); seedGates(brain, spec.seed); - mobs.add(mob); + LABELS.put(mob, ENTS.size()); + ENTS.add(mob); brains.add(brain); seeds.add(spec.seed); } level.getRandom().setSeed(s.levelSeed); + // Loot drawn from random sequences starts afresh in every scenario. + this.getRandomSequences().clear(); SOUNDS.clear(); Method tickTime = method(ServerLevel.class, "tickTime"); Object manager = get(level, "entityManager"); Method managerTick = method(manager.getClass(), "tick"); - for (int i = 0; i < mobs.size(); i++) print(0, i, mobs.get(i)); + Map watched = new java.util.LinkedHashMap<>(); + for (int[] box : s.watches) + for (int y = box[1]; y <= box[4]; y++) + for (int z = box[2]; z <= box[5]; z++) + for (int x = box[0]; x <= box[3]; x++) { + BlockPos pos = new BlockPos(x + s.originX, y, z + s.originZ); + watched.put(pos, level.getBlockState(pos)); + } + for (int i = 0; i < ENTS.size(); i++) print(0, i, ENTS.get(i)); for (int t = 1; t <= s.ticks; t++) { + if (s.daycycle) this.clockManager().setTotalTicks(clock, s.time + t); + for (Object[] e : s.timed) if ((Integer) e[0] == t) place((String[]) e[1], level); level.environmentAttributes().invalidateTickCache(); level.updateSkyBrightness(); tickTime.invoke(level); @@ -502,30 +577,74 @@ public final class VanillaMobAiOracle { TracingRandom.tick = t; TracingRandom.on = tracing(s) && t >= traceFrom() && t <= traceTo(); SOUNDS.clear(); - for (int i = 0; i < mobs.size(); i++) { + for (int i = 0; i < ENTS.size(); i++) { // Villager.refreshBrain builds a new brain with new gates: seed those too. - if (mobs.get(i).getBrain() != brains.get(i)) { - brains.set(i, mobs.get(i).getBrain()); + if (ENTS.get(i) instanceof Mob m && m.getBrain() != brains.get(i)) { + brains.set(i, m.getBrain()); seedGates(brains.get(i), seeds.get(i)); } } - for (Mob mob : mobs) { - if (mob.isRemoved()) continue; - mob.checkDespawn(); - if (mob.isRemoved()) continue; - level.tickNonPassenger(mob); + for (Entity e : List.copyOf(ENTS)) { + if (e.isRemoved()) continue; + e.checkDespawn(); + if (e.isRemoved()) continue; + level.tickNonPassenger(e); } managerTick.invoke(manager); - for (int i = 0; i < mobs.size(); i++) print(t, i, mobs.get(i)); + // What the tick spawned (babies, golems, dropped items) ticks from the next one, + // in the order it was added, with a seeded random of its own. + List fresh = new ArrayList<>(); + for (Entity e : level.getAllEntities()) + if (!(e instanceof Player) && !LABELS.containsKey(e) && (e instanceof Mob || e instanceof net.minecraft.world.entity.item.ItemEntity)) fresh.add(e); + fresh.sort(java.util.Comparator.comparingInt(Entity::getId)); + for (Entity e : fresh) { + int index = ENTS.size(); + long seed = spawnSeed(index); + LABELS.put(e, index); + ENTS.add(e); + seeds.add(seed); + if (e instanceof Mob mob) { + if (tracing(s)) field(Entity.class, "random").set(mob, new TracingRandom(0L, TRACE, index)); + mob.getRandom().setSeed(seed); + @SuppressWarnings("unchecked") + Map> sensors = (Map>) get(mob.getBrain(), "sensors"); + for (Sensor sensor : sensors.values()) sensor.randomlyDelayStart(mob.getRandom()); + seedGates(mob.getBrain(), seed); + brains.add(mob.getBrain()); + } else { + brains.add(null); + } + } + for (int i = 0; i < ENTS.size(); i++) print(t, i, ENTS.get(i)); for (String sound : SOUNDS) out.println(t + " sound " + sound); + for (var w : watched.entrySet()) { + BlockState now = level.getBlockState(w.getKey()); + if (now != w.getValue()) { + w.setValue(now); + BlockPos p = w.getKey(); + out.println(t + " block " + (p.getX() - s.originX) + "," + p.getY() + "," + (p.getZ() - s.originZ) + " " + stateName(now)); + } + } for (String line : TRACE) out.println(line); TRACE.clear(); } - for (Mob mob : mobs) mob.discard(); + for (Entity e : ENTS) e.discard(); managerTick.invoke(manager); out.flush(); } + /** The random seed of the entity a scenario spawned at this index. */ + static long spawnSeed(int index) { return 1000L + 7919L * index; } + + static String stateName(BlockState state) { + StringBuilder sb = new StringBuilder(BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString()); + List props = new ArrayList<>(); + state.getValues().forEach(v -> props.add(v.toString())); + props.sort(null); + if (!props.isEmpty()) sb.append('[').append(String.join(",", props)).append(']'); + return sb.toString(); + } + /** * Every GateBehavior (RunOne and the gates of TradeWithVillager and VillagerMakeLove) shuffles * its behaviours with its own ShufflingList random, which RandomSource.create() seeds from the @@ -549,7 +668,8 @@ public final class VanillaMobAiOracle { static String who(Entity e) { if (e == null) return "none"; if (e instanceof ServerPlayer) return "player"; - return "e" + e.getId(); + Integer label = LABELS.get(e); + return "e" + (label != null ? 100000 + label : e.getId()); } static String goals(GoalSelector selector) { @@ -582,13 +702,24 @@ public final class VanillaMobAiOracle { return v.getClass().getSimpleName(); } - void print(int t, int i, Mob m) throws Exception { + void print(int t, int i, Entity e) throws Exception { StringBuilder sb = new StringBuilder(); sb.append(t).append(' ').append(i); - if (m.isRemoved()) { - out.println(sb.append(" removed ").append(m.getRemovalReason())); + if (e.isRemoved()) { + out.println(sb.append(" removed ").append(e.getRemovalReason())); return; } + if (e instanceof ItemEntity item) { + sb.append("\tp ").append(d(item.getX())).append(',').append(d(item.getY())).append(',').append(d(item.getZ())); + Vec3 v = item.getDeltaMovement(); + sb.append("\tv ").append(d(v.x)).append(',').append(d(v.y)).append(',').append(d(v.z)); + sb.append("\tg ").append(item.onGround() ? 1 : 0).append(item.horizontalCollision ? 1 : 0); + sb.append("\titem ").append(stack(item.getItem())).append(' ').append(item.getAge()).append(' ') + .append(field(ItemEntity.class, "pickupDelay").getInt(item)); + out.println(sb); + return; + } + Mob m = (Mob) e; sb.append("\tp ").append(d(m.getX())).append(',').append(d(m.getY())).append(',').append(d(m.getZ())); Vec3 v = m.getDeltaMovement(); sb.append("\tv ").append(d(v.x)).append(',').append(d(v.y)).append(',').append(d(v.z)); @@ -629,9 +760,52 @@ public final class VanillaMobAiOracle { mem.sort(null); sb.append("\tmem ").append(String.join(" ", mem)); } + if (m instanceof Villager v) sb.append("\tvx ").append(villager(v)); out.println(sb); } + static String stack(net.minecraft.world.item.ItemStack stack) { + if (stack.isEmpty()) return "-"; + return BuiltInRegistries.ITEM.getKey(stack.getItem()).getPath() + "*" + stack.getCount(); + } + + static String uuidLabel(UUID uuid) { + if (uuid.equals(PLAYER_UUID)) return "player"; + for (Entity e : ENTS) if (e.getUUID().equals(uuid)) return who(e); + return uuid.toString(); + } + + /** A villager's data, food, inventory slots, gossip and offers. */ + static String villager(Villager v) throws Exception { + StringBuilder sb = new StringBuilder(); + var data = v.getVillagerData(); + sb.append("prof ").append(data.profession().unwrapKey().get().identifier().getPath()).append(" lvl ").append(data.level()) + .append(" xp ").append(v.getVillagerXp()).append(" food ").append(field(Villager.class, "foodLevel").getInt(v)) + .append(" age ").append(v.getAge()); + List slots = new ArrayList<>(); + var inv = v.getInventory(); + for (int k = 0; k < inv.getContainerSize(); k++) slots.add(stack(inv.getItem(k))); + while (!slots.isEmpty() && slots.getLast().equals("-")) slots.removeLast(); + sb.append(" inv ").append(slots.isEmpty() ? "-" : String.join(",", slots)); + List gossips = new ArrayList<>(); + v.getGossips().getGossipEntries().forEach((uuid, types) -> types.forEach((type, value) -> + gossips.add(uuidLabel(uuid) + ":" + type.getSerializedName() + "=" + value))); + gossips.sort(null); + sb.append(" gossip ").append(gossips.isEmpty() ? "-" : String.join(",", gossips)); + sb.append(" rep ").append(v.getGossips().getReputation(PLAYER_UUID, x -> true)); + sb.append(" sleep ").append(v.getSleepingPos().map(Server::pos).orElse("-")); + Object offers = get(v, "offers"); + if (offers != null) { + List list = new ArrayList<>(); + for (var o : (net.minecraft.world.item.trading.MerchantOffers) offers) { + list.add(stack(o.getBaseCostA()) + "+" + stack(o.getCostB()) + ">" + stack(o.getResult()) + "/" + o.getUses() + "/" + + o.getMaxUses() + "/" + o.getDemand() + "/" + o.getSpecialPriceDiff()); + } + sb.append(" offers ").append(list.isEmpty() ? "-" : String.join(",", list)); + } + return sb.toString(); + } + static String name(MemoryModuleType type) { return BuiltInRegistries.MEMORY_MODULE_TYPE.getKey(type).getPath(); } diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 5730d8b3d..2ea3f347a 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -88,6 +88,8 @@ def write_scenarios(path, chosen): lines.append(f'origin {ox} {oz}') for line in body: f = line.split() + # `at TICK block ...` changes blocks before that tick; `watch` boxes stay relative. + head, f = (f[:2], f[2:]) if f[0] == 'at' else ([], f) if f[0] == 'player': f[1] = repr(float(f[1]) + ox) f[3] = repr(float(f[3]) + oz) @@ -102,7 +104,7 @@ def write_scenarios(path, chosen): f[k] = str(int(f[k]) + ox) for k in (3, 6): f[k] = str(int(f[k]) + oz) - lines.append(' '.join(f)) + lines.append(' '.join(head + f)) lines.append('end') path.write_text('\n'.join(lines) + '\n') @@ -120,6 +122,9 @@ def parse(path): if parts[1] == 'sound': cur['sounds'].setdefault(t, []).append(parts[2]) continue + if parts[1] == 'block': + cur.setdefault('blocks', {}).setdefault(t, []).append(parts[2]) + continue if parts[1] == 'trace': cur.setdefault('trace', {}).setdefault(t, []).append(parts[2]) continue @@ -210,12 +215,14 @@ def compare(vanilla, rust, fields=None): report.extend(' ' + d for d in diffs[:12]) if first is not None: clean = False - # Sounds: first differing tick. - for t in sorted(set(v['sounds']) | set(r['sounds'])): - if v['sounds'].get(t, []) != r['sounds'].get(t, []): - report.append(f'{name}: sounds differ at tick {t}: vanilla {v["sounds"].get(t, [])} | horizon {r["sounds"].get(t, [])}') - clean = False - break + # Sounds and watched block changes: first differing tick. + for kind in ('sounds', 'blocks'): + va, ra = v.get(kind, {}), r.get(kind, {}) + for t in sorted(set(va) | set(ra)): + if va.get(t, []) != ra.get(t, []): + report.append(f'{name}: {kind} differ at tick {t}: vanilla {va.get(t, [])} | horizon {ra.get(t, [])}') + clean = False + break totals['clean'] += clean if clean: report.append(f'{name}: all {len(v["ticks"])} ticks match') From e0a025c5bdc94a3d737d6e2a0e83f197e4e2a9f0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 00:27:35 +0200 Subject: [PATCH 2/5] Compare villager gossip and breeding with vanilla Gossip and gifts between villagers (TradeWithVillager) move into the library so the mob_ai probe runs them as the game does; both villagers now lock their gaze on each other, as lockGazeAndWalkToEachOther does. The probe reads the oracle's villager flags, prints villager data (food, inventory, gossip, reputation) and adds babies as they are born. The oracle seeds TriggerGate's shuffles too, which were left to the clock. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 284 +++++++++++++++--- crates/horizon-client/src/game/villagers.rs | 112 ++----- crates/horizon-client/src/gossip.rs | 9 + crates/horizon-client/src/mobs.rs | 1 + crates/horizon-client/src/mobs/villager.rs | 103 +++++++ .../horizon-client/src/mobs/villager_brain.rs | 32 +- .../horizonlab/parity/VanillaMobAiOracle.java | 37 ++- tools/test_mob_ai_parity.py | 28 ++ 8 files changed, 446 insertions(+), 160 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index df0d70b62..c3d6a5605 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -223,56 +223,144 @@ fn goals(m: &Mob, names: Vec<&'static str>) -> String { .join("|") } -fn seen(m: &Mob) -> Seen { - Seen { - id: m.id, - species: m.species(), - position: m.position, - bounds: m.bounds(), - eye_y: m.eye_y(), - alive: m.alive(), - baby: m.is_baby(), - in_love: if m.species() == Species::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, - health: m.health, - variant: m.extra.variant, - color: m.extra.color, - job: (m.species() == Species::Villager) - .then_some(m.extra.home) - .flatten(), - bed: (m.species() == Species::Villager) - .then_some(m.extra.bed) - .flatten(), - yaw: m.yaw, - velocity: m.velocity, - leash: m.extra.leash, - caravan: horizon_client::mobs::caravan::head_of(m), - delay: m.extra.ints[5], - hurt_by: m.ai.last_hurt_by.map(|w| (w, m.ai.last_hurt_by_time)), - active_raid: horizon_client::mobs::raider::has_active_raid(m), - player_rep: 0, - pushable: m.pushable(), - category: m.category(), - potential_job: horizon_client::mobs::villager_brain::potential_job_site(m), - meeting: (m.species() == Species::Villager) - .then_some(m.extra.meeting) - .flatten(), - profession: m.extra.variant2, - xp: horizon_client::mobs::villager::xp(m), - stats: [ - f64::from(m.attrs.max_health), - m.extra.vector[0], - m.attrs.speed, - ], +/// The oracle's villager flags: profession, level, xp, food, inventory, +/// gossip about the player and the last sleep. +fn villager_flag(m: &mut Mob, flag: &str) { + use horizon_client::mobs::villager; + let (k, v) = flag + .split_once('=') + .unwrap_or_else(|| panic!("unknown mob flag {flag}")); + match k { + "profession" => { + let p = horizon_client::mobs::render::PROFESSIONS + .iter() + .position(|p| *p == v) + .expect("profession"); + villager::set_profession(m, p as u8); + } + "level" => m.extra.variant3 = v.parse().unwrap(), + "xp" => { + m.extra.trade.get_or_insert_with(Default::default).xp = v.parse().unwrap(); + } + "food" => villager::ext_mut(m).food_level = v.parse().unwrap(), + "inv" => { + for item in v.split(',') { + let (name, count) = item.split_once('*').unwrap_or((item, "1")); + villager::ext_mut(m) + .inventory + .push(horizon_client::items::ItemStack::new( + &if name.contains(':') { + name.to_owned() + } else { + format!("minecraft:{name}") + }, + count.parse().unwrap(), + )); + } + } + "gossip" => { + let g: Vec<&str> = v.split(':').collect(); + assert_eq!(g[0], "player", "gossip about the player only"); + let kind = horizon_client::gossip::GossipType::from_id(g[1]).expect("gossip type"); + villager::ext_mut(m) + .gossips + .add(PLAYER_UUID, kind, g[2].parse().unwrap()); + } + "slept" => villager::ext_mut(m).last_slept = Some(v.parse().unwrap()), + _ => panic!("unknown mob flag {flag}"), } } +/// The random seed of the entity a scenario spawns at this index (the +/// oracle's `spawnSeed`). +fn spawn_seed(index: usize) -> i64 { + 1000 + 7919 * index as i64 +} + +/// Villager events that act at once in vanilla (`TradeWithVillager` and +/// `VillagerMakeLove` write the other villager directly). +fn villager_events( + mobs: &mut Vec, + events: &mut Vec, + from: usize, + w: &MobWorld, + types: &MobTypes, + items: &Items, + born: &mut Vec, + day_time: i64, +) { + use horizon_client::mobs::villager; + let index = |mobs: &[Mob], id: u32| { + mobs.iter() + .position(|m| m.id == id && m.species() == Species::Villager) + }; + let mut i = from; + while i < events.len() { + match events[i] { + MobEvent::VillagerMeet { mob, other } => { + 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) + }); + assert!( + meeting.thrown.is_empty(), + "villagers toss items: not modelled here" + ); + } + events.remove(i); + } + MobEvent::VillagerBirth { parent, partner } => { + events.remove(i); + let (Some(a), Some(b)) = (index(mobs, parent), index(mobs, partner)) else { + continue; + }; + villager::ext_mut(&mut mobs[a]).eat_and_digest(); + villager::ext_mut(&mut mobs[b]).eat_and_digest(); + let p = mobs[a].position; + let from = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; + let Some(bed) = villager::take_vacant_bed(mobs, from, |x, y, z| { + w.prop(x, y, z, "part") == Some("head") + && w.prop(x, y, z, "occupied") == Some("false") + }) else { + continue; + }; + // Villager.getBreedOffspring: half the biome's type (plains + // here), a quarter each parent's. + let roll = horizon_core::random::RandomSource::next_double(&mut mobs[a].random); + let variant = if roll < 0.5 { + 0 + } else if roll < 0.75 { + mobs[a].extra.variant + } else { + mobs[b].extra.variant + }; + mobs[a].extra.age = 6000; + mobs[b].extra.age = 6000; + let index = mobs.len() + born.len(); + let kind = types.types.get("minecraft:villager").expect("villager"); + let mut child = Mob::new(100_000 + index as u32, Arc::new(kind.clone()), p, 0.0); + child.persistent = true; + child.extra.variant = variant; + child.extra.variant2 = villager::NONE; + child.extra.age = -24000; + child.extra.bed = Some(bed); + let seed = spawn_seed(index); + child.random = LegacyRandom::new(seed); + horizon_client::mobs::villager_brain::init(&mut child, w.game_time, day_time, seed); + born.push(child); + } + _ => i += 1, + } + } +} + +/// The player's UUID (the oracle's `PLAYER_UUID`). +const PLAYER_UUID: [i32; 4] = [0, 0x1234, 0, 0x5678]; + +fn seen(m: &Mob) -> Seen { + m.seen(Some(PLAYER_UUID)) +} + /// The probe's mobs as a creaking heart sees them: creakings it creates take /// the n-th seed from 1000, as the oracle's do. struct Host<'a> { @@ -479,9 +567,95 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) { if let Some((acts, mem)) = brain { let _ = write!(out, "\tact {acts}\tmem {mem}"); } + if m.species() == Species::Villager { + let _ = write!(out, "\tvx {}", villager(m)); + } out.push('\n'); } +fn stack(s: &horizon_client::items::ItemStack) -> String { + if s.count == 0 { + return "-".into(); + } + format!("{}*{}", s.item.trim_start_matches("minecraft:"), s.count) +} + +/// The oracle's `villager`: data, food, inventory, gossip, sleep and offers. +fn villager(m: &Mob) -> String { + use horizon_client::mobs::villager; + let e = villager::ext(m); + let mut slots: Vec = (0..8) + .map(|k| { + e.and_then(|e| e.inventory.get(k)) + .map_or_else(|| "-".to_owned(), stack) + }) + .collect(); + while slots.last().is_some_and(|s| s == "-") { + slots.pop(); + } + // Villagers gossip about players only. + let label = |t: [i32; 4]| { + if t == PLAYER_UUID { + "player".to_owned() + } else { + format!("{t:?}") + } + }; + let mut gossips: Vec = e + .map(|e| { + e.gossips + .entries() + .map(|(t, k, v)| format!("{}:{}={v}", label(t), k.id())) + .collect() + }) + .unwrap_or_default(); + gossips.sort(); + let join = |v: &[String]| { + if v.is_empty() { + "-".to_owned() + } else { + v.join(",") + } + }; + let mut s = format!( + "prof {} lvl {} xp {} food {} age {} inv {} gossip {} rep {} sleep {}", + horizon_client::mobs::render::PROFESSIONS[m.extra.variant2 as usize % 15], + m.extra.variant3.max(1), + villager::xp(m), + e.map_or(0, |e| e.food_level), + m.extra.age, + join(&slots), + join(&gossips), + e.map_or(0, |e| e.gossips.reputation(PLAYER_UUID)), + match (villager::sleeping(m), m.extra.bed) { + (true, Some(b)) => format!("{},{},{}", b[0], b[1], b[2]), + _ => "-".into(), + } + ); + if let Some(t) = m.extra.trade.as_ref().filter(|t| !t.offers.is_empty()) { + let offers: Vec = t + .offers + .iter() + .map(|o| { + format!( + "{}+{}>{}/{}/{}/{}/{}", + stack(&o.base_cost_a.stack), + o.cost_b + .as_ref() + .map_or_else(|| "-".to_owned(), |c| stack(&c.stack)), + stack(&o.result), + o.uses, + o.max_uses, + o.demand, + o.special_price_diff + ) + }) + .collect(); + s.push_str(&format!(" offers {}", join(&offers))); + } + s +} + fn main() -> horizon_client::Result<()> { let args: Vec = std::env::args().skip(1).collect(); if args.len() != 3 { @@ -608,7 +782,7 @@ fn main() -> horizon_client::Result<()> { let n: u32 = x[8..].parse().unwrap(); m.extra.leash = Some(horizon_client::mobs::leash::Holder::Mob(100_000 + n)); } - other => panic!("unknown mob flag {other}"), + other => villager_flag(&mut m, other), } } m.random = LegacyRandom::new(spec.seed); @@ -657,7 +831,7 @@ fn main() -> horizon_client::Result<()> { velocity: Vec3::ZERO, yaw: 0.0, hero: false, - uuid: [0, 0x1234, 0, 0x5678], + uuid: PLAYER_UUID, allies: Default::default(), } }); @@ -767,6 +941,7 @@ fn main() -> horizon_client::Result<()> { #[allow(unused_mut)] // filled only with the rng-trace feature let mut traces: Vec = Vec::new(); let mut pushes = Vec::new(); + let mut born = Vec::new(); for i in 0..mobs.len() { if mobs[i].removed { continue; @@ -790,6 +965,16 @@ fn main() -> horizon_client::Result<()> { m.removed = true; } horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from); + villager_events( + &mut mobs, + &mut events, + from, + &w, + &types, + &items, + &mut born, + s.time, + ); // ServerLevel ticks entities one after another: the ones // after this mob see it as it is now. if let Some(e) = snapshot.iter_mut().find(|e| e.id == mobs[i].id) { @@ -822,6 +1007,7 @@ fn main() -> horizon_client::Result<()> { added.append(&mut host.added); } drop(w); + mobs.append(&mut born); mobs.append(&mut added); for e in &heart_events { match e { diff --git a/crates/horizon-client/src/game/villagers.rs b/crates/horizon-client/src/game/villagers.rs index cbf3d015b..35377a3cc 100644 --- a/crates/horizon-client/src/game/villagers.rs +++ b/crates/horizon-client/src/game/villagers.rs @@ -59,68 +59,13 @@ impl Game<'_> { }; 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; + let meeting = villager::meet(&mut self.mobs, ia, ib, now, |item| { + items.get(item).map_or(64, |i| i.max_stack) + }); + for stack in meeting.thrown { + self.villager_throw(meeting.from, meeting.eye, meeting.to, stack); } - // 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 { + if meeting.gossiped { self.villager_golem_check(a, 5); } } @@ -269,41 +214,18 @@ impl Game<'_> { } /// `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 = 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) + villager::take_vacant_bed(&self.mobs, from, |x, y, z| { + let state = self.world.block(x, y, z); + !self.res.facts.is_air(state) + && *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") + }) + }) + }) } fn particles_at(&mut self, kind: &'static str, at: [f64; 3]) { if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) { diff --git a/crates/horizon-client/src/gossip.rs b/crates/horizon-client/src/gossip.rs index 63cc7e265..9a964a3e6 100644 --- a/crates/horizon-client/src/gossip.rs +++ b/crates/horizon-client/src/gossip.rs @@ -110,6 +110,15 @@ impl Gossips { pub fn clear(&mut self) { self.map.clear(); } + /// Every (target, type, value) held. + pub fn entries(&self) -> impl Iterator + '_ { + self.map.iter().flat_map(|(t, e)| { + GossipType::ALL + .into_iter() + .filter(move |k| e[k.index()] != 0) + .map(move |k| (*t, k, e[k.index()])) + }) + } pub fn get(&self, target: Target, kind: GossipType) -> i32 { self.map.get(&target).map_or(0, |e| e[kind.index()]) } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 33626e8fb..d4168c404 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1054,6 +1054,7 @@ pub fn apply_brain_events(mobs: &mut [Mob], events: &mut Vec, from: us MobEvent::LockGaze { mob, partner } => { if let Some(m) = mobs.iter_mut().find(|m| m.id == mob) { animal_brain::lock_gaze(m, partner); + villager_brain::lock_gaze_half(m, Who::Mob(partner)); } events.remove(i); } diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index 5f26183b8..4b344a0d3 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -536,6 +536,109 @@ pub fn seen(m: &Mob) -> Seen { golem_detected, } } +/// What `TradeWithVillager.tick` hands over: stacks tossed from the first +/// villager's hand (`from`, its eye height) toward the second (`to`), and +/// whether the gossip happened (`spawnGolemIfNeeded` follows). +pub struct Meeting { + pub thrown: Vec, + pub from: horizon_core::geometry::Vec3, + pub eye: f64, + pub to: horizon_core::geometry::Vec3, + pub gossiped: bool, +} +/// `TradeWithVillager.tick` for villagers `a` and `b` (indices into `mobs`): +/// `Villager.gossip` (at most once in 1200 ticks for both), then surplus +/// food and wanted wares taken out of `a`'s inventory. +pub fn meet( + mobs: &mut [Mob], + a: usize, + b: usize, + now: i64, + max_stack: impl Fn(&str) -> u32, +) -> Meeting { + let ready = ext(&mobs[a]).is_none_or(|e| e.can_gossip(now)) + && ext(&mobs[b]).is_none_or(|e| e.can_gossip(now)); + if ready { + let source = ext(&mobs[b]).map(|e| e.gossips.clone()).unwrap_or_default(); + let me = &mut mobs[a]; + let mut random = me.random.clone(); + let e = ext_mut(me); + e.gossips.transfer_from(&source, &mut random, 10); + e.last_gossip_time = now; + me.random = random; + ext_mut(&mut mobs[b]).last_gossip_time = now; + } + // Surplus food goes to a hungry neighbour (farmers hand it to anyone). + let farmer = is_farmer(&mobs[a]); + let wants_more = ext(&mobs[b]).is_none_or(Ext::wants_more_food); + let excess = ext(&mobs[a]).is_some_and(Ext::has_excess_food); + let mut thrown = Vec::new(); + if excess + && (farmer || wants_more) + && let Some(s) = + ext_mut(&mut mobs[a]).take_half_stack(|s| food_points(&s.item) > 0, &max_stack) + { + thrown.push(s); + } + // A farmer's wheat. + if farmer + && ext(&mobs[a]).is_some_and(|e| e.count_item("minecraft:wheat") > 32) + && let Some(s) = + ext_mut(&mut mobs[a]).take_half_stack(|s| &*s.item == "minecraft:wheat", &max_stack) + { + thrown.push(s); + } + // Wares the neighbour's profession asks for and ours does not. + let theirs = requested_items(&mobs[b]); + let mine = requested_items(&mobs[a]); + let wanted: Vec<&str> = theirs + .iter() + .copied() + .filter(|i| !mine.contains(i)) + .collect(); + if !wanted.is_empty() + && let Some(s) = + ext_mut(&mut mobs[a]).take_half_stack(|s| wanted.contains(&&*s.item), &max_stack) + { + thrown.push(s); + } + Meeting { + thrown, + from: mobs[a].position, + eye: mobs[a].eye_y(), + to: mobs[b].position, + gossiped: ready, + } +} +/// `PoiManager.take(HOME, ..., 48)`: the nearest bed head no villager has +/// claimed (`free_head`: a bed head that is not occupied). +pub fn take_vacant_bed( + mobs: &[Mob], + from: [i32; 3], + mut free_head: impl FnMut(i32, i32, i32) -> bool, +) -> Option<[i32; 3]> { + let claimed: Vec<[i32; 3]> = mobs + .iter() + .filter(|m| m.species() == Species::Villager) + .filter_map(|m| m.extra.bed) + .collect(); + 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 d = (x - from[0]).pow(2) + (y - from[1]).pow(2) + (z - from[2]).pow(2); + if d <= 48 * 48 + && best.is_none_or(|(b, _)| d < b) + && free_head(x, y, z) + && !claimed.contains(&[x, y, z]) + { + best = Some((d, [x, y, z])); + } + } + } + } + best.map(|(_, p)| p) +} /// `Villager.canBreed`: enough food, awake and an adult. pub fn can_breed(m: &Mob) -> bool { m.species() == Species::Villager diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 987dca76f..aefaaf3e4 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -1609,13 +1609,7 @@ impl B { } t.begin(cx); let target = mem(m).interaction_target.value().unwrap(); - let mm = mem(m); - mm.look_target.set(Tracker::Entity(target, true)); - mm.walk_target.set(WalkTarget { - target: Tracker::Entity(target, true), - speed: 0.5, - close: 2, - }); + lock_gaze(m, target, cx); true } B::MakeLove { t, birth } => { @@ -1628,7 +1622,7 @@ impl B { } t.begin(cx); let target = mem(m).breed_target.value().unwrap(); - lock_gaze(m, target); + lock_gaze(m, target, cx); *birth = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0)); true } @@ -2853,6 +2847,7 @@ impl B { && i.position.distance_squared(m.position) <= 5.0 { let Who::Mob(other) = target else { return }; + lock_gaze(m, target, cx); cx.events.push(MobEvent::VillagerMeet { mob: m.id, other }); } } @@ -2870,7 +2865,7 @@ impl B { .target_info(target) .is_some_and(|t| t.position.distance_squared(m.position) <= 5.0) { - lock_gaze(m, target); + lock_gaze(m, target, cx); if now >= *birth { cx.events.push(MobEvent::VillagerBirth { parent: m.id, @@ -3366,8 +3361,23 @@ fn breeding_possible(m: &mut Mob, w: &MobWorld) -> bool { && super::villager::can_breed(m) && w.seen(id).is_some_and(|s| s.in_love) } -/// `BehaviorUtils.lockGazeAndWalkToEachOther`, this villager's half. -fn lock_gaze(m: &mut Mob, target: Who) { +/// `BehaviorUtils.lockGazeAndWalkToEachOther`: this villager's half, and +/// the other villager's through a `LockGaze` event. +fn lock_gaze(m: &mut Mob, target: Who, cx: &mut Bx) { + lock_gaze_half(m, target); + if let Who::Mob(other) = target { + cx.events.push(MobEvent::LockGaze { + mob: other, + partner: m.id, + }); + } +} +/// One villager's half of `lockGazeAndWalkToEachOther`: look at the other +/// and walk to it. +pub fn lock_gaze_half(m: &mut Mob, target: Who) { + if super::villager::ext(m).is_none_or(|e| e.brain.is_none()) { + return; + } let mm = mem(m); mm.look_target.set(Tracker::Entity(target, true)); mm.walk_target.set(WalkTarget { 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 b9c93ae42..d16869cc8 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -779,10 +779,37 @@ public final class VanillaMobAiOracle { } static void seedGate(Object behavior, long seed) throws Exception { - if (!(behavior instanceof GateBehavior)) return; - ShufflingList list = (ShufflingList) field(GateBehavior.class, "behaviors").get(behavior); - field(ShufflingList.class, "random").set(list, new net.minecraft.world.level.levelgen.LegacyRandomSource(seed)); - for (Object child : list) seedGate(child, seed); + seedLists(behavior, seed, java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>()), 0); + } + + /** + * Seeds every ShufflingList a behaviour holds: a GateBehavior's, and the ones TriggerGate + * captures in its lambdas (BehaviorBuilder's one-shots), found through their fields. + */ + static void seedLists(Object o, long seed, Set seen, int depth) throws Exception { + if (o == null || depth > 8 || !seen.add(o)) return; + if (o instanceof ShufflingList list) { + field(ShufflingList.class, "random").set(list, new net.minecraft.world.level.levelgen.LegacyRandomSource(seed)); + for (Object child : list) seedLists(child, seed, seen, depth + 1); + return; + } + String name = o.getClass().getName(); + if (!name.startsWith("net.minecraft.world.entity.ai.behavior") || o instanceof Enum) return; + for (Class c = o.getClass(); c != null && c.getName().startsWith("net.minecraft"); c = c.getSuperclass()) { + for (Field f : c.getDeclaredFields()) { + if (java.lang.reflect.Modifier.isStatic(f.getModifiers()) || f.getType().isPrimitive()) continue; + f.setAccessible(true); + Object v = f.get(o); + if (v instanceof Iterable it && !(v instanceof ShufflingList)) { + for (Object x : it) seedLists(x, seed, seen, depth + 1); + } else if (v instanceof com.mojang.datafixers.util.Pair pair) { + seedLists(pair.getFirst(), seed, seen, depth + 1); + seedLists(pair.getSecond(), seed, seen, depth + 1); + } else { + seedLists(v, seed, seen, depth + 1); + } + } + } } static String who(Entity e) { @@ -880,7 +907,7 @@ public final class VanillaMobAiOracle { mem.sort(null); sb.append("\tmem ").append(String.join(" ", mem)); } - if (m instanceof Villager v) sb.append("\tvx ").append(villager(v)); + if (m instanceof Villager villager) sb.append("\tvx ").append(villager(villager)); out.println(sb); } diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index d9c1594a9..691c1ada7 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -77,6 +77,34 @@ def scenarios(): 'player 12.5 -60 0.5', 'mob minecraft:villager 0.5 -60 0.5 0 51 persistent', ]) + # Two villagers gossip (TradeWithVillager): what one heard of the player + # passes to the other, weakened, once in 1200 ticks; idle and at the bell. + gossips = ('gossip=player:minor_negative:100 gossip=player:major_positive:15 ' + 'gossip=player:trading:20 gossip=player:minor_positive:3') + for name, opts, extra in [('villager_gossip_idle', 'time=100', []), + ('villager_gossip_bell', 'time=9500', ['block 0 -60 -6 minecraft:bell'])]: + add(name, 400, extra + [ + 'player 14.5 -60 0.5', + f'mob minecraft:villager 0.5 -60 0.5 0 61 persistent {gossips}', + 'mob minecraft:villager 2.5 -60 0.5 180 62 persistent gossip=player:minor_positive:50', + ], opts) + # Two villagers with bread breed (VillagerMakeLove): they eat, a baby is + # born and takes a free bed, the parents rest for 6000 ticks. + beds = [] + for x in (-6, -3, 3, 6): + beds += [f'block {x} -60 6 minecraft:red_bed[facing=north,part=foot]', + f'block {x} -60 5 minecraft:red_bed[facing=north,part=head]'] + for name, seeds in [('villager_breed', (71, 72)), ('villager_breed_2', (73, 74))]: + add(name, 900, beds + [ + 'player 14.5 -60 0.5', + f'mob minecraft:villager 0.5 -60 0.5 0 {seeds[0]} persistent inv=bread*3', + f'mob minecraft:villager 2.5 -60 0.5 180 {seeds[1]} persistent inv=bread*3 food=4', + ], 'time=100') + # Too little food: no breeding. + add('villager_breed_hungry', 400, beds[:2] + [ + 'mob minecraft:villager 0.5 -60 0.5 0 75 persistent inv=bread*2', + 'mob minecraft:villager 2.5 -60 0.5 180 76 persistent inv=bread*3', + ], 'time=100') # Breezes: idle, and fighting a player near, in, and beyond the inner jump circle. add('breeze_alone', 200, ['mob minecraft:breeze 0.5 -60 0.5 90 61 persistent']) add('breeze_player', 200, ['player 8.5 -60 0.5', 'mob minecraft:breeze 0.5 -60 0.5 0 62 persistent']) From 52a419ac31564eedf9033a641b336b71c2933033 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 00:35:40 +0200 Subject: [PATCH 3/5] Match villager births and footsteps on bed edges The parent's half of VillagerMakeLove.tryToGiveBirth (eating, the child's bed and type, resting) runs in its own tick, before it ages; the partner's follows as an event. A baby's NearestBedSensor keeps its bed when the reused path heads elsewhere, as vanilla checks for a POI there. Footsteps come from the block under the feet (Entity.mainSupportingBlockPos), not the column below the centre. The oracle faces newborns' heads with their bodies (LivingEntity draws the head yaw from Math.random), and the breeding scenarios leave one free bed per section (PoiManager hands them out in hash order). Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 29 ++---- crates/horizon-client/src/game/creatures.rs | 6 +- crates/horizon-client/src/game/villagers.rs | 57 ++++------- crates/horizon-client/src/mobs.rs | 6 +- crates/horizon-client/src/mobs/living.rs | 99 ++++++++++++++++++- crates/horizon-client/src/mobs/villager.rs | 11 +-- .../horizon-client/src/mobs/villager_brain.rs | 41 +++++++- .../horizonlab/parity/VanillaMobAiOracle.java | 4 + tools/test_mob_ai_parity.py | 4 +- 9 files changed, 182 insertions(+), 75 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index c3d6a5605..b0b09581e 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -309,38 +309,27 @@ fn villager_events( } events.remove(i); } - MobEvent::VillagerBirth { parent, partner } => { + MobEvent::VillagerBirth { + parent, + partner, + child, + } => { events.remove(i); let (Some(a), Some(b)) = (index(mobs, parent), index(mobs, partner)) else { continue; }; - villager::ext_mut(&mut mobs[a]).eat_and_digest(); villager::ext_mut(&mut mobs[b]).eat_and_digest(); - let p = mobs[a].position; - let from = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; - let Some(bed) = villager::take_vacant_bed(mobs, from, |x, y, z| { - w.prop(x, y, z, "part") == Some("head") - && w.prop(x, y, z, "occupied") == Some("false") - }) else { + let Some((bed, variant)) = child else { continue; }; - // Villager.getBreedOffspring: half the biome's type (plains - // here), a quarter each parent's. - let roll = horizon_core::random::RandomSource::next_double(&mut mobs[a].random); - let variant = if roll < 0.5 { - 0 - } else if roll < 0.75 { - mobs[a].extra.variant - } else { - mobs[b].extra.variant - }; - mobs[a].extra.age = 6000; mobs[b].extra.age = 6000; let index = mobs.len() + born.len(); let kind = types.types.get("minecraft:villager").expect("villager"); + let p = mobs[a].position; let mut child = Mob::new(100_000 + index as u32, Arc::new(kind.clone()), p, 0.0); child.persistent = true; - child.extra.variant = variant; + // The flat world is all plains (type 0). + child.extra.variant = variant.unwrap_or(0); child.extra.variant2 = villager::NONE; child.extra.age = -24000; child.extra.bed = Some(bed); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index bc59fef4d..bd958893f 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -914,7 +914,11 @@ impl Game<'_> { } MobEvent::CureZombieVillager { mob } => self.cure_zombie_villager(mob), MobEvent::VillagerMeet { mob, other } => self.villager_meet(mob, other), - MobEvent::VillagerBirth { parent, partner } => self.villager_birth(parent, partner), + MobEvent::VillagerBirth { + parent, + partner, + child, + } => self.villager_birth(parent, partner, child), MobEvent::GolemCheck { mob, needed } => self.villager_golem_check(mob, needed), MobEvent::Firework { at, color, flight } => { self.villager_firework(at, color, flight) diff --git a/crates/horizon-client/src/game/villagers.rs b/crates/horizon-client/src/game/villagers.rs index 35377a3cc..f0bdf5009 100644 --- a/crates/horizon-client/src/game/villagers.rs +++ b/crates/horizon-client/src/game/villagers.rs @@ -8,7 +8,6 @@ use horizon_client::{ 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] @@ -164,46 +163,39 @@ impl Game<'_> { /// `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) { + pub(super) fn villager_birth( + &mut self, + parent: u32, + partner: u32, + child: Option<([i32; 3], Option)>, + ) { 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| { + let Some((bed, variant)) = child else { 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 p = self.mobs[i].position; + self.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 { + let variant = variant.unwrap_or_else(|| { + let facts = self.biome_facts( + from.x.floor() as i32, + from.y.floor() as i32, + from.z.floor() as i32, + ); spawning::villager_type(&facts) - } else if roll < 0.75 { - kind_of(&self.mobs[ia]) - } else { - kind_of(&self.mobs[ib]) - }; + }); + self.mobs[ib].extra.age = 6000; 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; @@ -212,21 +204,6 @@ impl Game<'_> { } 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 mut known: HashMap = HashMap::new(); - villager::take_vacant_bed(&self.mobs, from, |x, y, z| { - let state = self.world.block(x, y, z); - !self.res.facts.is_air(state) - && *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") - }) - }) - }) - } 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); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index d4168c404..9e0f55097 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -798,10 +798,14 @@ pub enum MobEvent { mob: u32, other: u32, }, - /// Two villagers make a baby. + /// Two villagers make a baby (`VillagerMakeLove.tryToGiveBirth`): the + /// parent has eaten and, with a bed for the child, rests; the partner + /// eats, and rests too if `child` holds the child's bed and type + /// (`None`: the biome's). VillagerBirth { parent: u32, partner: u32, + child: Option<([i32; 3], Option)>, }, /// A villager asks whether enough neighbours want an iron golem. GolemCheck { diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 03d2f201f..e0a147116 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -132,6 +132,38 @@ impl MobWorld<'_> { .map(|shape| shape.boxes().iter().map(|b| b.move_by(offset)).collect()) .unwrap_or_default() } + /// `Level.findSupportingBlock`: of the blocks whose collision shape + /// meets `area`, the one whose centre is nearest `from` (ties: the + /// greatest by `Vec3i.compareTo`, y then z then x). + pub fn supporting_block(&self, area: Aabb, from: Vec3) -> Option<[i32; 3]> { + use horizon_core::geometry::Axis; + let range = |axis| { + (area.min(axis) - 1.0e-7).floor() as i32 - 1 + ..=(area.max(axis) + 1.0e-7).floor() as i32 + 1 + }; + let mut best: Option<(f64, [i32; 3])> = None; + for y in range(Axis::Y) { + for z in range(Axis::Z) { + for x in range(Axis::X) { + if !self + .block_collision_boxes(x, y, z) + .iter() + .any(|b| b.intersects(area)) + { + continue; + } + let d = (f64::from(x) + 0.5 - from.x).powi(2) + + (f64::from(y) + 0.5 - from.y).powi(2) + + (f64::from(z) + 0.5 - from.z).powi(2); + let greater = |b: [i32; 3]| (y, z, x) > (b[1], b[2], b[0]); + if best.is_none_or(|(bd, b)| d < bd || d == bd && greater(b)) { + best = Some((d, [x, y, z])); + } + } + } + } + best.map(|(_, p)| p) + } pub fn no_collision(&self, b: Aabb) -> bool { let mut scene = SceneCollisions { world: self.world, @@ -346,7 +378,8 @@ impl Mob { let full = (moved.length() * f64::from(0.6_f32)) as f32; let horizontal = ((moved.x * moved.x + moved.z * moved.z).sqrt() * f64::from(0.6_f32)) as f32; - let on = self.on_pos(1.0e-5); + let supporting = self.supporting_block(w, moved); + let on = self.supported_on_pos(w, supporting, 1.0e-5); let state = w.world.block(on[0], on[1], on[2]); let climbable = w.facts.get(state).name.as_ref() == "minecraft:powder_snow" || w.has_tag("minecraft:climbable", &w.facts.get(state).name); @@ -354,7 +387,7 @@ impl Mob { steps.move_dist += if climbable { full } else { horizontal }; steps.fly_dist += full; if steps.move_dist > steps.next_step && !w.facts.is_air(state) { - let legacy = self.on_pos(0.2); + let legacy = self.supported_on_pos(w, supporting, 0.2); let legacy_state = w.world.block(legacy[0], legacy[1], legacy[2]); let produced = !w.facts.is_air(legacy_state) && (self.on_ground || climbable) @@ -397,6 +430,68 @@ impl Mob { fn fluids_swimming(&self) -> bool { false } + /// `Entity.checkSupportingBlock` after a move: on the ground, the block + /// under the feet (`mainSupportingBlockPos`), looked for again where + /// the mob came from if none is under it now. + fn supporting_block(&self, w: &MobWorld, moved: Vec3) -> Option<[i32; 3]> { + if !self.on_ground { + return None; + } + let b = self.bounds(); + use horizon_core::geometry::Axis; + let area = Aabb::new( + Vec3::new(b.min(Axis::X), b.min(Axis::Y) - 1.0e-6, b.min(Axis::Z)), + Vec3::new(b.max(Axis::X), b.min(Axis::Y), b.max(Axis::Z)), + ); + w.supporting_block(area, self.position).or_else(|| { + let back = Vec3::new(-moved.x, 0.0, -moved.z); + let shifted = Aabb::new( + Vec3::new( + area.min(Axis::X) + back.x, + area.min(Axis::Y), + area.min(Axis::Z) + back.z, + ), + Vec3::new( + area.max(Axis::X) + back.x, + area.max(Axis::Y), + area.max(Axis::Z) + back.z, + ), + ); + w.supporting_block(shifted, self.position) + }) + } + /// `Entity.getOnPos(offset)` with a supporting block: its column (its + /// own position for fences, walls and gates up to half a block down). + fn supported_on_pos( + &self, + w: &MobWorld, + supporting: Option<[i32; 3]>, + offset: f32, + ) -> [i32; 3] { + let Some(p) = supporting else { + return self.on_pos(offset); + }; + if offset <= 1.0e-5 { + return p; + } + let name = &w.facts.get(w.world.block(p[0], p[1], p[2])).name; + let tall = [ + "minecraft:fences", + "minecraft:walls", + "minecraft:fence_gates", + ] + .iter() + .any(|t| w.has_tag(t, name)); + if offset <= 0.5 && tall { + p + } else { + [ + p[0], + (self.position.y - f64::from(offset)).floor() as i32, + p[2], + ] + } + } /// Entity.getOnPos(offset) without a supporting block record. pub fn on_pos(&self, offset: f32) -> [i32; 3] { [ diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index 4b344a0d3..f568cb47b 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -610,18 +610,13 @@ pub fn meet( gossiped: ready, } } -/// `PoiManager.take(HOME, ..., 48)`: the nearest bed head no villager has -/// claimed (`free_head`: a bed head that is not occupied). +/// `PoiManager.take(HOME, ..., 48)`: the nearest bed head not `claimed` +/// (`free_head`: a bed head that is not occupied). pub fn take_vacant_bed( - mobs: &[Mob], + claimed: &[[i32; 3]], from: [i32; 3], mut free_head: impl FnMut(i32, i32, i32) -> bool, ) -> Option<[i32; 3]> { - let claimed: Vec<[i32; 3]> = mobs - .iter() - .filter(|m| m.species() == Species::Villager) - .filter_map(|m| m.extra.bed) - .collect(); 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 { diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index aefaaf3e4..7bd33c89f 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -663,7 +663,7 @@ fn sense_bed(m: &mut Mob, w: &MobWorld, lr: &mut LegacyRandom) { let mut cache = std::mem::take(&mut brain_mut(m).bed_cache); let mut tried = 0; let mut targets = Vec::new(); - for p in homes { + for &p in &homes { if cache.iter().any(|(q, _)| *q == p) { continue; } @@ -679,8 +679,12 @@ fn sense_bed(m: &mut Mob, w: &MobWorld, lr: &mut LegacyRandom) { } else { m.create_path_to_any(w, &targets, 1) }; + // createPath hands back the current path when it still heads for a + // target position it was asked: only a bed (a POI) counts. if let Some(path) = path.filter(|p| p.reached) { - mem(m).nearest_bed.set(path.target); + if homes.contains(&path.target) { + mem(m).nearest_bed.set(path.target); + } } else if tried < 5 { cache.retain(|(_, until)| *until >= last_update); } @@ -2867,9 +2871,27 @@ impl B { { lock_gaze(m, target, cx); if now >= *birth { + // The parent's half happens in its own tick: it eats, + // takes a bed for the child, picks its type and rests. + super::villager::ext_mut(m).eat_and_digest(); + let child = take_bed_for_child(m, cx.w).map(|bed| { + // Villager.getBreedOffspring: half the biome's type, + // a quarter each parent's. + let roll = m.random.next_double(); + let variant = if roll < 0.5 { + None + } else if roll < 0.75 { + Some(m.extra.variant) + } else { + Some(cx.w.seen(partner).map_or(m.extra.variant, |s| s.variant)) + }; + m.extra.age = 6000; + (bed, variant) + }); cx.events.push(MobEvent::VillagerBirth { parent: m.id, partner, + child, }); } else if m.random.next_int_bound(35).unwrap_or(1) == 0 { let mut p = vec![m.position]; @@ -3361,6 +3383,21 @@ fn breeding_possible(m: &mut Mob, w: &MobWorld) -> bool { && super::villager::can_breed(m) && w.seen(id).is_some_and(|s| s.in_love) } +/// `VillagerMakeLove.takeVacantBed`: a bed head no villager has claimed. +fn take_bed_for_child(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { + let claimed: Vec<[i32; 3]> = w + .others + .iter() + .filter(|s| s.species == Species::Villager && s.id != m.id) + .filter_map(|s| s.bed) + .chain(m.extra.bed) + .collect(); + let p = m.position; + let from = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; + super::villager::take_vacant_bed(&claimed, from, |x, y, z| { + w.prop(x, y, z, "part") == Some("head") && w.prop(x, y, z, "occupied") != Some("true") + }) +} /// `BehaviorUtils.lockGazeAndWalkToEachOther`: this villager's half, and /// the other villager's through a `LockGaze` event. fn lock_gaze(m: &mut Mob, target: Who, cx: &mut Bx) { 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 d16869cc8..f6a5e9bb6 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -704,6 +704,10 @@ public final class VanillaMobAiOracle { ENTS.add(e); seeds.add(seed); if (e instanceof Mob mob) { + // LivingEntity's constructor turns the head at random (Math.random): + // face it the way the body does, as the probe's newborns. + mob.setYHeadRot(mob.getYRot()); + mob.yHeadRotO = mob.getYRot(); if (tracing(s)) field(Entity.class, "random").set(mob, new TracingRandom(0L, TRACE, index)); mob.getRandom().setSeed(seed); @SuppressWarnings("unchecked") diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 691c1ada7..9abc3f960 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -90,8 +90,10 @@ def scenarios(): ], opts) # Two villagers with bread breed (VillagerMakeLove): they eat, a baby is # born and takes a free bed, the parents rest for 6000 ticks. + # PoiManager.take hands out the free beds of a section in hash order: + # the parents claim the two near them, the child gets the only one left. beds = [] - for x in (-6, -3, 3, 6): + for x in (-6, 3, 6): beds += [f'block {x} -60 6 minecraft:red_bed[facing=north,part=foot]', f'block {x} -60 5 minecraft:red_bed[facing=north,part=head]'] for name, seeds in [('villager_breed', (71, 72)), ('villager_breed_2', (73, 74))]: From 389d2f9549553d51637a5f9eac4cc668ca2a27aa Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 00:50:18 +0200 Subject: [PATCH 4/5] Adopt only villagers and creakings born during a mob_ai scenario Animal babies and dropped items stay out of the comparison, as before the merge: the probe does not model them. Co-Authored-By: Claude Opus 5.5 --- .../java/dev/horizonlab/parity/VanillaMobAiOracle.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) 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 f6a5e9bb6..6185d65f0 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -682,11 +682,12 @@ public final class VanillaMobAiOracle { } if (!heartPositions.isEmpty()) level.tickBlockEntities(); managerTick.invoke(manager); - // What the tick spawned (babies, golems, dropped items) ticks from the next one, - // in the order it was added, with a seeded random of its own. + // Villagers the tick spawned (babies) and a heart's creakings tick from the next + // one, in the order they were added, with a seeded random of their own. Other + // newcomers (animal babies, dropped items) are left out, as the probe leaves them. List fresh = new ArrayList<>(); for (Entity e : level.getAllEntities()) - if (!(e instanceof Player) && !LABELS.containsKey(e) && (e instanceof Mob || e instanceof net.minecraft.world.entity.item.ItemEntity)) fresh.add(e); + if (!LABELS.containsKey(e) && (e instanceof Villager || created.contains(e))) fresh.add(e); fresh.sort(java.util.Comparator.comparingInt(Entity::getId)); for (Entity e : fresh) { int index = ENTS.size(); From 5ce4b9585db5ccef804b59ff7aa8e174bf20aee0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 00:51:30 +0200 Subject: [PATCH 5/5] Satisfy clippy Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/examples/mob_ai_probe.rs | 2 +- crates/horizon-client/src/mobs/villager_brain.rs | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index b0b09581e..729ac88f1 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -280,7 +280,7 @@ fn spawn_seed(index: usize) -> i64 { /// Villager events that act at once in vanilla (`TradeWithVillager` and /// `VillagerMakeLove` write the other villager directly). fn villager_events( - mobs: &mut Vec, + mobs: &mut [Mob], events: &mut Vec, from: usize, w: &MobWorld, diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 7bd33c89f..4d94ca2bb 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -4142,7 +4142,11 @@ pub fn seen_memories( let Some(mm) = mem_ref(m) else { return (None, None, false, None); }; - let path = mm.path.present().then(|| m.ai.nav.path.as_ref()).flatten(); + let path = mm + .path + .present() + .then_some(m.ai.nav.path.as_ref()) + .flatten(); let nodes = path.filter(|p| !p.is_done()).map(|p| { let n = |i: usize| [p.nodes[i].x, p.nodes[i].y, p.nodes[i].z]; ((p.next > 0).then(|| n(p.next - 1)), n(p.next))