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] 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')