diff --git a/crates/horizon-client/examples/entity_components_probe.rs b/crates/horizon-client/examples/entity_components_probe.rs new file mode 100644 index 000000000..0d4a51e8c --- /dev/null +++ b/crates/horizon-client/examples/entity_components_probe.rs @@ -0,0 +1,89 @@ +#![forbid(unsafe_code)] +//! Runs tools/test_entity_components_parity.py's entities and advancement +//! entity predicates through `horizon_client::advancements::entity`, with the +//! variant component `mobs::finalize::species_variant_component` reports. +use horizon_client::{ + Result, + advancements::{EntityView, World, entity}, + mobs::{ + Species, + finalize::{species_variant_component, variant_index}, + }, +}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; + +/// Nothing but the entity: these predicates read only its type and components. +struct Empty; +impl World for Empty { + fn dimension(&self) -> &str { + "minecraft:overworld" + } + fn biome(&self, _: [i32; 3]) -> String { + "minecraft:plains".into() + } + fn structures(&self, _: [i32; 3]) -> Vec { + Vec::new() + } + fn block(&self, _: [i32; 3]) -> (String, BTreeMap) { + ("minecraft:air".into(), BTreeMap::new()) + } + fn fluid(&self, _: [i32; 3]) -> Option { + None + } + fn can_see_sky(&self, _: [i32; 3]) -> bool { + true + } + fn light(&self, _: [i32; 3]) -> i32 { + 15 + } + fn smokey(&self, _: [i32; 3]) -> bool { + false + } + fn in_tag(&self, _: &str, _: &str, _: &str) -> bool { + false + } +} + +fn species(id: &str) -> Species { + match id { + "minecraft:wolf" => Species::Wolf, + "minecraft:cat" => Species::Cat, + "minecraft:frog" => Species::Frog, + "minecraft:pig" => Species::Pig, + "minecraft:cow" => Species::Cow, + "minecraft:chicken" => Species::Chicken, + other => panic!("no species for {other}"), + } +} + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let input = BufReader::new(File::open(&args[1])?); + let mut out = BufWriter::new(File::create(&args[2])?); + for (n, line) in input.lines().enumerate() { + let c: Value = serde_json::from_str(&line?)?; + writeln!(out, "== {n}")?; + let kind = c["type"].as_str().unwrap(); + let s = species(kind); + let variant = variant_index(s, c["variant"].as_str().unwrap()); + let view = EntityView { + kind: kind.to_owned(), + position: [0.5, 64.0, 0.5], + components: species_variant_component(s, variant) + .map(|(id, v)| (id.to_owned(), v)) + .into_iter() + .collect(), + ..Default::default() + }; + for p in c["predicates"].as_array().unwrap() { + writeln!(out, "{}", entity(p, &view, &Empty, [2.5, 64.0, 0.5]))?; + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 2d62c2b97..fb111d8d6 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -294,6 +294,8 @@ pub struct EntityView { pub struck: Vec, pub fishing_open_water: Option, pub variant: Option, + /// The data components the entity reports (`Entity.get`): id and value. + pub components: Vec<(String, String)>, } fn range_f(v: &Value, x: f64) -> bool { match v { @@ -442,6 +444,26 @@ pub fn location(v: &Value, p: [f64; 3], w: &dyn World) -> bool { } true } +/// `DataComponentExactPredicate.test` on an entity: every expected +/// component equals what the entity reports (absent ones never match). +fn components(expected: &Value, have: &[(String, String)]) -> bool { + let full = |id: &str| { + if id.contains(':') { + id.to_owned() + } else { + format!("minecraft:{id}") + } + }; + expected.as_object().is_some_and(|o| { + o.iter().all(|(id, want)| { + let id = full(id); + want.as_str().is_some_and(|want| { + have.iter() + .any(|(k, v)| full(k) == id && full(v) == full(want)) + }) + }) + }) +} /// `EntityPredicate` (26.x keyed sub-predicates). pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> bool { if v.is_null() { @@ -521,7 +543,8 @@ pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> boo "minecraft:type_specific/fishing_hook" => p["in_open_water"] .as_bool() .is_none_or(|want| e.fishing_open_water == Some(want)), - "minecraft:components" | "minecraft:predicates" => true, + "minecraft:components" => components(p, &e.components), + "minecraft:predicates" => true, _ => false, }; if !ok { diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 428d7da97..9323ed8ea 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -338,6 +338,10 @@ impl Game<'_> { baby: m.is_baby(), on_ground: m.on_ground, equipment, + components: horizon_client::mobs::finalize::variant_component(m) + .map(|(id, value)| (id.to_owned(), value)) + .into_iter() + .collect(), ..Default::default() } } diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index 0e5a0a2ec..ea90af835 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -1984,6 +1984,25 @@ pub fn variant_index(s: Species, name: &str) -> u8 { }; i.unwrap_or(0) as u8 } +/// The variant data component a mob reports (`Entity.get`, e.g. +/// `Wolf.get(DataComponents.WOLF_VARIANT)`): component id and registry entry. +pub fn variant_component(m: &Mob) -> Option<(&'static str, String)> { + species_variant_component(m.species(), m.extra.variant) +} +/// [`variant_component`] of a species with the game's variant index. +pub fn species_variant_component(s: Species, variant: u8) -> Option<(&'static str, String)> { + let component = match s { + Species::Wolf => "minecraft:wolf/variant", + Species::Cat => "minecraft:cat/variant", + Species::Frog => "minecraft:frog/variant", + Species::Pig => "minecraft:pig/variant", + Species::Cow => "minecraft:cow/variant", + Species::Chicken => "minecraft:chicken/variant", + Species::ZombieNautilus => "minecraft:zombie_nautilus/variant", + _ => return None, + }; + Some((component, format!("minecraft:{}", variant_name(s, variant)))) +} /// The registry name of the game's variant index. pub fn variant_name(s: Species, index: u8) -> &'static str { let i = index as usize; diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityComponentsOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityComponentsOracle.java new file mode 100644 index 000000000..d27a4c80e --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityComponentsOracle.java @@ -0,0 +1,116 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.serialization.JsonOps; +import java.io.PrintWriter; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import java.util.function.Predicate; +import net.minecraft.advancements.predicates.entity.EntityPredicate; +import net.minecraft.core.*; +import net.minecraft.core.component.DataComponentType; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.RegistryOps; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.RandomSource; +import net.minecraft.world.DifficultyInstance; +import net.minecraft.world.damagesource.DamageSources; +import net.minecraft.world.entity.*; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.entity.EntityTypeTest; +import net.minecraft.world.level.gamerules.GameRules; +import net.minecraft.world.phys.AABB; +import net.minecraft.world.phys.Vec3; + +/** + * Original oracle for the entity predicates advancements match tamed, leashed + * or bred animals with: real entities made with EntityType.create(LOAD) on a + * level stand-in, given the case's variant through Entity.setComponent (the + * variant data component, e.g. minecraft:wolf/variant), then tested with the + * real EntityPredicate (decoded from the case with the registries' ops), which + * reads the variant back through Entity.get for its minecraft:components. + */ +public final class VanillaEntityComponentsOracle { + static Object unsafe; + static Method allocate, putObject, objectFieldOffset; + + static void put(Object target, Class owner, String field, Object value) throws Exception { + Field f = owner.getDeclaredField(field); + long offset = (long) objectFieldOffset.invoke(unsafe, f); + putObject.invoke(unsafe, target, offset, value); + } + + static final class Lvl extends ServerLevel { + Lvl() { super(null, null, null, null, null, null, false, 0L, List.of(), false); } + net.minecraft.server.MinecraftServer fake; + RegistryAccess registries; + GameRules rules; + @Override public net.minecraft.server.MinecraftServer getServer() { return fake; } + int next = 1; + @Override public RegistryAccess registryAccess() { return registries; } + @Override public net.minecraft.world.Difficulty getDifficulty() { return net.minecraft.world.Difficulty.NORMAL; } + @Override public long getGameTime() { return 0L; } + @Override public int getNextEntityId() { return next++; } + @Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); } + @Override public GameRules getGameRules() { return rules; } + @Override public boolean addFreshEntity(Entity entity) { return true; } + @Override public List getEntities(EntityTypeTest type, AABB bb, Predicate selector) { return new ArrayList<>(); } + net.minecraft.world.attribute.EnvironmentAttributeSystem attributes; + @Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes() { return attributes; } + @Override public int getSeaLevel() { return 63; } + @Override public DifficultyInstance getCurrentDifficultyAt(BlockPos pos) { return new DifficultyInstance(net.minecraft.world.Difficulty.NORMAL, 0L, 0L, 0.0F); } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public static void main(String[] args) throws Exception { + ParityData.init(); + var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + unsafeField.setAccessible(true); + unsafe = unsafeField.get(null); + allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + putObject = unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class); + objectFieldOffset = unsafe.getClass().getMethod("objectFieldOffset", Field.class); + RegistryAccess access = ParityData.access; + Lvl level = (Lvl) allocate.invoke(unsafe, Lvl.class); + level.registries = access; + // A server that only answers debug subscribers (PathNavigation asks). + var server = (net.minecraft.server.MinecraftServer) allocate.invoke(unsafe, net.minecraft.server.dedicated.DedicatedServer.class); + put(server, net.minecraft.server.MinecraftServer.class, "debugSubscribers", allocate.invoke(unsafe, net.minecraft.util.debug.ServerDebugSubscribers.class)); + level.fake = server; + put(level, ServerLevel.class, "server", server); + level.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().build(); + level.rules = new GameRules(net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags()); + put(level, Level.class, "damageSources", new DamageSources(access)); + put(level, Level.class, "random", RandomSource.create(0L)); + var ops = RegistryOps.create(JsonOps.INSTANCE, ParityData.lookup); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + int n = 0; + for (var line : (Iterable) lines::iterator) { + var c = JsonParser.parseString(line).getAsJsonObject(); + out.println("== " + n++); + String type = c.get("type").getAsString(); + Entity entity = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(type)).create(level, EntitySpawnReason.LOAD); + if (c.has("variant")) { + // The species' variant component and registry: minecraft:/variant + // holds an entry of minecraft:_variant. + String species = Identifier.parse(type).getPath(); + var component = (DataComponentType) BuiltInRegistries.DATA_COMPONENT_TYPE.getValue(Identifier.parse("minecraft:" + species + "/variant")); + ResourceKey> registry = ResourceKey.createRegistryKey(Identifier.parse("minecraft:" + species + "_variant")); + var holder = access.lookupOrThrow(registry).getOrThrow(ResourceKey.create(registry, Identifier.parse(c.get("variant").getAsString()))); + entity.setComponent(component, holder); + } + entity.setPos(0.5, 64.0, 0.5); + for (var p : c.getAsJsonArray("predicates")) { + var predicate = EntityPredicate.CODEC.parse(ops, p).getOrThrow(); + out.println(predicate.matches(level, new Vec3(2.5, 64.0, 0.5), entity)); + } + } + } + System.exit(0); + } +} diff --git a/tools/test_entity_components_parity.py b/tools/test_entity_components_parity.py new file mode 100644 index 000000000..fe9fcac96 --- /dev/null +++ b/tools/test_entity_components_parity.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Compare the entity predicates of the variant advancements (A Complete +Catalogue, The Whole Pack, Leash all frog variants) with the pinned client: the +real EntityPredicate of each criterion, decoded from the advancement files, +tested on real wolves, cats, frogs, pigs, cows and chickens of every variant +(the variant data components Entity.get reports for minecraft:components).""" +import json +import random + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + +ADVANCEMENTS = ('complete_catalogue', 'whole_pack', 'leash_all_frog_variants') +SPECIES = ('wolf', 'cat', 'frog', 'pig', 'cow', 'chicken') + + +def predicates(): + """Every criterion's entity predicate, plus the components alone and + with the wrong type.""" + folder = lab.LOCAL / 'horizon-client/26.3/data/minecraft/advancement/husbandry' + out = [] + for name in ADVANCEMENTS: + data = json.loads((folder / f'{name}.json').read_text()) + for criterion in data['criteria'].values(): + predicate = criterion['conditions']['entity']['predicate'] + out.append(predicate) + components = {'minecraft:components': predicate['minecraft:components']} + out.append(components) + out.append(dict(components, **{'minecraft:entity_type': 'minecraft:pig'})) + return out + + +def variants(species): + folder = lab.LOCAL / f'horizon-client/26.3/data/minecraft/{species}_variant' + return sorted('minecraft:' + p.stem for p in folder.glob('*.json')) + + +def make_cases(build): + path = build / 'cases.jsonl' + every = predicates() + rng = random.Random(0x56415249) + count = 0 + with path.open('w') as out: + for species in SPECIES: + for variant in variants(species): + listed = every + [rng.choice(every) for _ in range(8)] + case = dict(type='minecraft:' + species, variant=variant, predicates=listed) + out.write(json.dumps(case, separators=(',', ':')) + '\n') + count += 1 + return path, count + + +def main(): + scope = ('The real EntityPredicate of every criterion of complete_catalogue, whole_pack and ' + 'leash_all_frog_variants (and their minecraft:components alone, or with another entity type), decoded ' + 'with the registries\' ops, on entities made with EntityType.create(LOAD) given each registered variant ' + 'of their species through Entity.setComponent. The trigger dispatch around them is not exercised.') + harness.differential( + 'rust-entity-components-parity', 'VanillaEntityComponentsOracle', 'entity_components_probe', make_cases, scope, + sources=[lab.ROOT / 'crates/horizon-client/src/advancements.rs', + lab.ROOT / 'crates/horizon-client/src/mobs/finalize.rs']) + + +if __name__ == '__main__': + main()