diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 9305f88ad..0eb215aa9 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -9,6 +9,10 @@ use horizon_client::{ block_entity_anim::Ticker, chunk::{MIN_Y, SECTIONS}, items::ItemStack, + mobs::{ + Species, + render::{PROFESSIONS, VILLAGER_TYPES}, + }, widgets, }; use horizon_core::geometry::Vec3; @@ -592,10 +596,20 @@ impl Game<'_> { } }; for m in self.mobs.iter().filter(|m| m.alive()) { + let mut v = json!({ "id": m.id, "kind": "mob", "health": m.health, "baby": m.is_baby(), "hurt_time": m.hurt_time }); + // VillagerData as this game knows it: on a client, what the + // server's synched data says. + if matches!(m.species(), Species::Villager | Species::ZombieVillager) { + v["villager"] = json!({ + "type": VILLAGER_TYPES[m.extra.variant as usize % VILLAGER_TYPES.len()], + "profession": PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()], + "level": m.extra.variant3, + }); + } push( [m.position.x, m.position.y, m.position.z], m.kind.id.as_ref(), - json!({ "id": m.id, "kind": "mob", "health": m.health, "baby": m.is_baby(), "hurt_time": m.hurt_time }), + v, ); } for item in &self.dropped { diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index a84998934..5573d0f87 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -3,12 +3,15 @@ //! `onSyncedDataUpdated`): what a client draws from it rather than from its //! own simulation, which a client of a server doesn't run. use super::Game; +use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; use horizon_client::mobs::{Mob, Species, tame}; use horizon_protocol::entity_data::Value; +use horizon_protocol::registry::Builtin; /// The values `apply` takes from one SetEntityData packet, by vanilla's entry /// indices (Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses). -fn apply(m: &mut Mob, values: &[(u8, i32, Value)]) { +/// `builtin` names the ids of built-in registries. +fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) { let species = m.species(); let baby = super::lan::baby_index(&m.kind.id); for (index, _, value) in values { @@ -42,16 +45,45 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)]) { (Species::Slime | Species::MagmaCube, 18, Value::Int(size)) => { m.extra.size = (*size).clamp(1, 127); } + // Villager.DATA_VILLAGER_DATA and ZombieVillager's (after + // Zombie's three): what VillagerProfessionLayer draws. + (Species::Villager, 19, Value::Ids(data)) + | (Species::ZombieVillager, 20, Value::Ids(data)) => villager_data(m, data, builtin), _ => {} } } } +/// VillagerData as the network sends it: the type and the profession by +/// their built-in registry ids, then the level. +fn villager_data(m: &mut Mob, data: &[i32], builtin: &Builtin) { + let &[kind, profession, level] = data else { + return; + }; + let index = |registry: &str, id: i32, names: &[&str]| { + let name = builtin + .get(registry)? + .name(id)? + .strip_prefix("minecraft:")?; + names.iter().position(|n| *n == name).map(|i| i as u8) + }; + if let Some(t) = index("minecraft:villager_type", kind, &VILLAGER_TYPES) { + m.extra.variant = t; + } + if let Some(p) = index("minecraft:villager_profession", profession, &PROFESSIONS) { + m.extra.variant2 = p; + } + m.extra.variant3 = level.clamp(0, i32::from(u8::MAX)) as u8; +} + impl Game<'_> { /// SetEntityData for a mob of the server's. pub(super) fn remote_mob_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { + let Some(r) = &self.remote else { + return; + }; if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { - apply(m, values); + apply(m, values, &r.builtin); } } } @@ -72,11 +104,23 @@ mod tests { /// A mob of the prepared resources' type `kind`, as a client spawns it /// (None without the resources). - fn mob(kind: &str) -> Option { - let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + fn root() -> std::path::PathBuf { + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../.local/horizon-client") - .join(horizon_core::VANILLA_VERSION); - let types = horizon_client::mobs::MobTypes::load(&root).ok()?; + .join(horizon_core::VANILLA_VERSION) + } + + /// The prepared resources' built-in registries (empty without them). + fn builtin() -> Builtin { + Builtin::load(&root().join("registries.json")).unwrap_or_default() + } + + fn apply(m: &mut Mob, values: &[(u8, i32, Value)]) { + super::apply(m, values, &builtin()); + } + + fn mob(kind: &str) -> Option { + let types = horizon_client::mobs::MobTypes::load(&root()).ok()?; let t = std::sync::Arc::new(types.types.get(kind)?.clone()); let mut m = Mob::new(1, t, horizon_core::geometry::Vec3::ZERO, 0.0); client_defaults(&mut m); @@ -133,4 +177,45 @@ mod tests { apply(&mut m, &[(0, s::BYTE, Value::Byte(0))]); assert_eq!(m.fire_ticks, 0); } + + #[test] + fn a_villager_takes_its_type_profession_and_level() { + let Some(mut m) = mob("minecraft:villager") else { + return; + }; + let registries = builtin(); + let id = |registry: &str, name: &str| registries.get(registry)?.id(name); + let (Some(desert), Some(farmer), Some(librarian)) = ( + id("minecraft:villager_type", "minecraft:desert"), + id("minecraft:villager_profession", "minecraft:farmer"), + id("minecraft:villager_profession", "minecraft:librarian"), + ) else { + return; + }; + let name = |m: &Mob| { + ( + VILLAGER_TYPES[m.extra.variant as usize], + PROFESSIONS[m.extra.variant2 as usize], + m.extra.variant3, + ) + }; + apply( + &mut m, + &[(19, s::VILLAGER_DATA, Value::Ids(vec![desert, farmer, 2]))], + ); + assert_eq!(name(&m), ("desert", "farmer", 2)); + // A job taken later: only the profession and the level change. + apply( + &mut m, + &[(19, s::VILLAGER_DATA, Value::Ids(vec![desert, librarian, 5]))], + ); + assert_eq!(name(&m), ("desert", "librarian", 5)); + // A zombie villager's data comes after Zombie's three entries. + let mut z = mob("minecraft:zombie_villager").unwrap(); + apply( + &mut z, + &[(20, s::VILLAGER_DATA, Value::Ids(vec![desert, farmer, 3]))], + ); + assert_eq!(name(&z), ("desert", "farmer", 3)); + } } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 42dd7ec53..3ece4b448 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -225,6 +225,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - knockback: the host hits the guest three times, then the guest the host, two seconds apart: each hit slides the victim as far as vanilla's does, 1.989 blocks (a guest's server-side velocity settles between hits; it used to add up, so each push went further). +- villagers: the guest sees each villager's and zombie villager's type, profession and level as the + host has them, and an unemployed villager that takes a composter becomes a farmer on + the guest too (the guest used to draw every villager as an unemployed plains one). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -5434,5 +5437,64 @@ CHECKS += ['knockback'] CHECK_FNS.update(knockback=check_knockback) +def check_villagers(host, guest, out): + """Villager.DATA_VILLAGER_DATA and ZombieVillager's reach the guest: summoned villagers show + their type, profession and level, and an unemployed villager that takes a composter placed + afterwards turns into a farmer on the guest too (VillagerProfessionLayer draws from that data).""" + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + x, y, z = gx, gy, gz + 5 + tag = 'vs_villager' + summoned = [('villager', -2, 'desert', 'librarian', 3), ('villager', 0, 'snow', 'weaponsmith', 5), + ('zombie_villager', 2, 'taiga', 'cleric', 2), ('villager', 4, 'plains', 'none', 1)] + + def villagers(game): + return {e['id']: e['villager'] for e in game.raw('entities', 16)['entities'] if 'villager' in e} + + seen = {} + try: + host('command', command='time set 2000') + host('command', command=f'fill {x - 4} {y - 1} {z - 3} {x + 6} {y - 1} {z + 4} minecraft:stone') + host('command', command=f'fill {x - 4} {y} {z - 3} {x + 6} {y + 3} {z + 4} minecraft:air') + for kind, dx, t, p, level in summoned: + # The unemployed one keeps its AI to take the job. + ai = '' if p == 'none' else 'NoAI:1b,Invulnerable:1b,' + host('command', command=f'summon minecraft:{kind} {x + dx + 0.5} {y} {z + 0.5} {{Tags:["{tag}"],{ai}' + f'PersistenceRequired:1b,Rotation:[180f,0f],' + f'VillagerData:{{type:"minecraft:{t}",profession:"minecraft:{p}",level:{level}}}}}') + guest.wait(20) + seen['summoned'] = {'host': villagers(host), 'guest': villagers(guest)} + host('command', command=f'setblock {x + 5} {y} {z + 2} minecraft:composter') + for waited in range(10, 1210, 10): + guest.wait(10) + farmers = [i for i, v in villagers(host).items() if v['profession'] == 'farmer'] + if farmers: + seen['ticks to the job'] = waited + break + guest.wait(10) + seen['job'] = {'host': villagers(host), 'guest': villagers(guest)} + guest('command', command=f'tp @s {x + 1.5} {y} {z - 2.5} 0 10') + guest.wait(10) + guest.shot(out, 'villagers') + finally: + host('command', command=f'kill @e[tag={tag}]') + host('command', command=f'fill {x - 4} {y} {z - 3} {x + 6} {y + 3} {z + 4} minecraft:air') + host('command', command='time set day') + host_view, guest_view = seen['summoned']['host'], seen['summoned']['guest'] + for _, _, t, p, level in summoned: + want = {'type': t, 'profession': p, 'level': level} + ids = [i for i, v in host_view.items() if v == want] + assert ids, f'the host lacks {want}: {seen}' + assert guest_view.get(ids[0]) == want, f'the guest sees {guest_view.get(ids[0])} for {want}: {seen}' + farmers = [i for i, v in seen['job']['host'].items() if v['profession'] == 'farmer'] + assert farmers, f'no villager took the job: {seen}' + assert seen['job']['guest'].get(farmers[0]) == seen['job']['host'][farmers[0]], \ + f'the guest missed the new job: {seen}' + return seen + + +CHECKS += ['villagers'] +CHECK_FNS.update(villagers=check_villagers) + + if __name__ == '__main__': main()