Add mob attribute and dimension parity harness
Adds a differential harness that instantiates every vanilla entity type on a detached server level and compares default attributes, standing dimensions and baby dimensions with Horizon's mob table. Baby donkeys and mules now use the vanilla half-size hitbox instead of 0.7 scale. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
//! Prints Horizon's mob attributes and dimensions in the format of
|
||||
//! `VanillaMobAttributesOracle` (tools/test_mob_attributes_parity.py).
|
||||
//!
|
||||
//! usage: mob_attributes_fixture RESOURCES OUTPUT
|
||||
use horizon_client::mobs::{Mob, MobTypes};
|
||||
use horizon_core::geometry::Vec3;
|
||||
use std::{fmt::Write as _, fs, path::Path, sync::Arc};
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let root = Path::new(
|
||||
args.get(1)
|
||||
.ok_or("usage: mob_attributes_fixture RESOURCES OUTPUT")?,
|
||||
);
|
||||
let types = MobTypes::load(root)?;
|
||||
let mut ids: Vec<&String> = types.types.keys().collect();
|
||||
ids.sort();
|
||||
let mut out = String::new();
|
||||
for id in ids {
|
||||
let kind = Arc::new(types.types[id].clone());
|
||||
let mut mob = Mob::new(1, kind.clone(), Vec3::new(0.0, 64.0, 0.0), 0.0);
|
||||
let d = mob.dims();
|
||||
let _ = write!(out, "{id}\tdim {:?} {:?} {:?}", d.0, d.1, d.2);
|
||||
let _ = write!(out, "\tscale {:?}", 1.0);
|
||||
let a = &mob.attrs;
|
||||
let _ = write!(
|
||||
out,
|
||||
"\tattrs max_health={:?} movement_speed={:?} attack_damage={:?} follow_range={:?}",
|
||||
f64::from(a.max_health),
|
||||
a.speed,
|
||||
f64::from(a.attack_damage),
|
||||
a.follow_range
|
||||
);
|
||||
let _ = write!(
|
||||
out,
|
||||
" flying_speed={:?} attack_knockback={:?} step_height={:?} armor={:?} armor_toughness={:?} knockback_resistance={:?} jump_strength={:?} gravity={:?} safe_fall_distance={:?} fall_damage_multiplier={:?} water_movement_efficiency={:?}",
|
||||
kind.flying_speed,
|
||||
kind.attack_knockback,
|
||||
kind.step_height,
|
||||
f64::from(kind.armor),
|
||||
f64::from(kind.armor_toughness),
|
||||
kind.knockback_resistance,
|
||||
kind.jump_strength,
|
||||
kind.gravity,
|
||||
kind.safe_fall_distance,
|
||||
kind.fall_damage_multiplier,
|
||||
kind.water_efficiency
|
||||
);
|
||||
mob.extra.age = -1;
|
||||
let b = mob.dims();
|
||||
let _ = write!(out, "\tbaby {:?} {:?} {:?}", b.0, b.1, b.2);
|
||||
out.push('\n');
|
||||
}
|
||||
fs::write(args.get(2).ok_or("missing OUTPUT")?, out)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -261,7 +261,7 @@ pub const ALL: &[Def] = &[
|
||||
"entity.donkey.death"
|
||||
],
|
||||
Some("entity.horse.step"),
|
||||
Baby::Scale(0.7, None)
|
||||
Baby::Scale(0.5, None)
|
||||
),
|
||||
def!(
|
||||
Mule,
|
||||
@@ -275,7 +275,7 @@ pub const ALL: &[Def] = &[
|
||||
"entity.mule.death"
|
||||
],
|
||||
Some("entity.horse.step"),
|
||||
Baby::Scale(0.7, None)
|
||||
Baby::Scale(0.5, None)
|
||||
),
|
||||
def!(
|
||||
Llama,
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.file.*;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.ai.attributes.*;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
|
||||
/**
|
||||
* Original oracle: instantiates every living entity type on a detached ServerLevel and prints
|
||||
* its live attribute map values, standing dimensions (adult and baby), age scale and the
|
||||
* base experience reward, one tab separated line per type.
|
||||
*/
|
||||
public final class VanillaMobAttributesOracle {
|
||||
static final class Level extends ServerLevel {
|
||||
Level() { super(null, null, null, null, null, null, false, 0L, java.util.List.of(), false); }
|
||||
net.minecraft.server.MinecraftServer fake;
|
||||
@Override public net.minecraft.server.MinecraftServer getServer() { return fake; }
|
||||
net.minecraft.core.RegistryAccess registries;
|
||||
@Override public net.minecraft.core.RegistryAccess registryAccess() { return registries; }
|
||||
@Override public net.minecraft.world.Difficulty getDifficulty() { return net.minecraft.world.Difficulty.NORMAL; }
|
||||
@Override public long getGameTime() { return 0L; }
|
||||
int next = 1;
|
||||
@Override public int getNextEntityId() { return next++; }
|
||||
@Override public net.minecraft.world.flag.FeatureFlagSet enabledFeatures() { return net.minecraft.world.flag.FeatureFlags.REGISTRY.allFlags(); }
|
||||
}
|
||||
|
||||
static String f(double v) { return Double.toString(v); }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
var uf = u.getDeclaredField("theUnsafe");
|
||||
uf.setAccessible(true);
|
||||
Object unsafe = uf.get(null);
|
||||
Method allocate = u.getMethod("allocateInstance", Class.class);
|
||||
Level level = (Level) allocate.invoke(unsafe, Level.class);
|
||||
var xp = Mob.class.getDeclaredMethod("getBaseExperienceReward", ServerLevel.class);
|
||||
xp.setAccessible(true);
|
||||
var ds = net.minecraft.server.dedicated.DedicatedServer.class;
|
||||
Object server = allocate.invoke(unsafe, ds);
|
||||
Object subs = allocate.invoke(unsafe, net.minecraft.util.debug.ServerDebugSubscribers.class);
|
||||
var sf = net.minecraft.server.MinecraftServer.class.getDeclaredField("debugSubscribers");
|
||||
sf.setAccessible(true);
|
||||
sf.set(server, subs);
|
||||
level.fake = (net.minecraft.server.MinecraftServer) server;
|
||||
var repo = net.minecraft.server.packs.repository.ServerPacksSource.createVanillaTrustedRepository();
|
||||
repo.reload();
|
||||
repo.setSelected(java.util.List.of("vanilla"));
|
||||
var resources = new net.minecraft.server.packs.resources.MultiPackResourceManager(net.minecraft.server.packs.PackType.SERVER_DATA, repo.openAllSelected());
|
||||
var layers = net.minecraft.server.RegistryLayer.createRegistryAccess();
|
||||
var staticTags = net.minecraft.tags.TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(net.minecraft.server.RegistryLayer.STATIC));
|
||||
var context = net.minecraft.tags.TagLoader.buildUpdatedLookups(layers.getAccessForLoading(net.minecraft.server.RegistryLayer.WORLD), staticTags);
|
||||
level.registries = net.minecraft.resources.RegistryDataLoader.load(resources, context, net.minecraft.resources.RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0])))) {
|
||||
for (var type : BuiltInRegistries.ENTITY_TYPE) {
|
||||
String id = BuiltInRegistries.ENTITY_TYPE.getKey(type).toString();
|
||||
Entity e;
|
||||
try {
|
||||
e = type.create(level, EntitySpawnReason.LOAD);
|
||||
} catch (Throwable t) {
|
||||
out.println(id + "\tFAIL\t" + t);
|
||||
continue;
|
||||
}
|
||||
if (e == null) { out.println(id + "\tNULL"); continue; }
|
||||
var sb = new StringBuilder(id);
|
||||
var d = e.getDimensions(Pose.STANDING);
|
||||
sb.append("\tdim ").append(f(d.width())).append(' ').append(f(d.height())).append(' ').append(f(d.eyeHeight()));
|
||||
if (e instanceof LivingEntity le) {
|
||||
sb.append("\tscale ").append(f(le.getAgeScale()));
|
||||
sb.append("\tattrs");
|
||||
for (var a : BuiltInRegistries.ATTRIBUTE.asHolderIdMap())
|
||||
if (le.getAttributes().hasAttribute(a))
|
||||
sb.append(' ').append(a.unwrapKey().orElseThrow().identifier().getPath()).append('=').append(f(le.getAttributeValue(a)));
|
||||
if (e instanceof AgeableMob am) {
|
||||
try {
|
||||
am.setBaby(true);
|
||||
var b = am.getDimensions(Pose.STANDING);
|
||||
sb.append("\tbaby ").append(f(b.width())).append(' ').append(f(b.height())).append(' ').append(f(b.eyeHeight()));
|
||||
} catch (Throwable t) { sb.append("\tbaby FAIL ").append(t); }
|
||||
} else if (e instanceof net.minecraft.world.entity.monster.zombie.Zombie z) {
|
||||
z.setBaby(true);
|
||||
var b = z.getDimensions(Pose.STANDING);
|
||||
sb.append("\tbaby ").append(f(b.width())).append(' ').append(f(b.height())).append(' ').append(f(b.eyeHeight()));
|
||||
}
|
||||
if (e instanceof Mob m) {
|
||||
try { sb.append("\txp ").append(xp.invoke(m, level)); } catch (Throwable t) { sb.append("\txp ?"); }
|
||||
}
|
||||
}
|
||||
out.println(sb);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+94
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare mob default attributes, dimensions (adult and baby) and the entity inventory with vanilla."""
|
||||
import argparse
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
|
||||
# Entity types that are not mobs (or are players): Horizon models them outside the mob table.
|
||||
# Horizon models these differently on purpose: slimes/magma cubes are created already sized (size 1,
|
||||
# vanilla applies setSize at spawn), and the phantom keeps its move control speed in attrs.speed.
|
||||
KNOWN = {('minecraft:slime', k) for k in ('max_health', 'movement_speed', 'attack_damage')} | \
|
||||
{('minecraft:magma_cube', k) for k in ('max_health', 'movement_speed', 'attack_damage')} | {('minecraft:phantom', 'movement_speed')}
|
||||
|
||||
|
||||
def parse(path):
|
||||
rows = {}
|
||||
for line in path.read_text(encoding='utf-8').splitlines():
|
||||
id, *fields = line.split('\t')
|
||||
row = {'raw': fields}
|
||||
for f in fields:
|
||||
key, _, rest = f.partition(' ')
|
||||
if key == 'attrs':
|
||||
row['attrs'] = {k: float(v) for k, v in (p.split('=') for p in rest.split())}
|
||||
elif key in ('dim', 'baby'):
|
||||
try:
|
||||
row[key] = [float(x) for x in rest.split()]
|
||||
except ValueError:
|
||||
pass
|
||||
elif key == 'scale':
|
||||
row['scale'] = float(rest)
|
||||
rows[id] = row
|
||||
return rows
|
||||
|
||||
|
||||
def close(a, b):
|
||||
return a == b or abs(a - b) <= 1e-6 * max(1.0, abs(a), abs(b)) or (math.isnan(a) and math.isnan(b))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--prepare', action='store_true')
|
||||
args = parser.parse_args()
|
||||
build = lab.LOCAL / 'rust-mob-attributes-parity'
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
if args.prepare:
|
||||
lab.prepare()
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAttributesOracle.java'
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
deps = os.pathsep.join(map(str, libraries))
|
||||
|
||||
def run(cmd, name):
|
||||
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
|
||||
subprocess.run(list(map(str, cmd)), cwd=lab.ROOT, check=True, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
|
||||
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
|
||||
run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaMobAttributesOracle', build / 'vanilla.txt'], 'java')
|
||||
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'mob_attributes_fixture'], 'compile-rust')
|
||||
binary = lab.ROOT / 'target/release/examples/mob_attributes_fixture'
|
||||
resources = lab.ROOT / '.local/horizon-client/26.3'
|
||||
run([binary, resources, build / 'rust.txt'], 'rust')
|
||||
vanilla, rust = parse(build / 'vanilla.txt'), parse(build / 'rust.txt')
|
||||
problems = []
|
||||
living = [i for i, r in vanilla.items() if 'attrs' in r]
|
||||
missing = [i for i in vanilla if i not in rust]
|
||||
(build / 'missing.txt').write_text('\n'.join(missing) + '\n')
|
||||
failed = [i for i, r in vanilla.items() if 'raw' in r and r['raw'][:1] == ['FAIL']]
|
||||
for id, v in vanilla.items():
|
||||
r = rust.get(id)
|
||||
if r is None:
|
||||
continue
|
||||
if 'dim' in v and 'dim' in r and not all(close(a, b) for a, b in zip(v['dim'], r['dim'])):
|
||||
problems.append(f'{id}: dim vanilla={v["dim"]} rust={r["dim"]}')
|
||||
if 'baby' in v and not all(close(a, b) for a, b in zip(v['baby'], r['baby'])):
|
||||
problems.append(f'{id}: baby vanilla={v["baby"]} rust={r["baby"]}')
|
||||
for k, x in v.get('attrs', {}).items():
|
||||
if (id, k) not in KNOWN and k in r['attrs'] and not close(x, r['attrs'][k]):
|
||||
problems.append(f'{id}: {k} vanilla={x} rust={r["attrs"][k]}')
|
||||
print(f'vanilla types {len(vanilla)} (living {len(living)}), Horizon mob types {len(rust)}, not in mob table {len(missing)}: {" ".join(m.split(":")[1] for m in missing)}')
|
||||
print('oracle could not instantiate:', ' '.join(f.split(':')[1] for f in failed))
|
||||
if problems:
|
||||
print('\n'.join(problems))
|
||||
raise SystemExit(f'{len(problems)} divergences')
|
||||
print('Mob attribute/dimension parity passed')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user