WIP: environment render parity harness
Work in progress on the environment rendering differential harness: a Rust fixture example, a vanilla oracle and the driver script. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
//! Environment attributes for differential tests against vanilla
|
||||
//! (tools/test_environment_render_parity.py): reads "dimension ticks rain
|
||||
//! thunder biome" lines and prints the sampled sky state as JSON lines.
|
||||
//!
|
||||
//! usage: environment_fixture RESOURCES INPUT OUTPUT
|
||||
use horizon_client::{
|
||||
biome::Biomes,
|
||||
environment::{Environment, apply_weather},
|
||||
};
|
||||
use std::{collections::HashMap, fmt::Write as _, fs, path::Path};
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let root = Path::new(
|
||||
args.get(1)
|
||||
.ok_or("usage: environment_fixture RESOURCES INPUT OUTPUT")?,
|
||||
);
|
||||
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
|
||||
let biomes = Biomes::load(root)?;
|
||||
let mut environments: HashMap<String, Environment> = HashMap::new();
|
||||
let mut out = String::new();
|
||||
for line in input.lines() {
|
||||
let f: Vec<&str> = line.split(' ').collect();
|
||||
let dimension = f[0];
|
||||
let environment = match environments.entry(dimension.to_owned()) {
|
||||
std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
|
||||
std::collections::hash_map::Entry::Vacant(e) => e.insert(Environment::load_dimension(
|
||||
root,
|
||||
dimension,
|
||||
dimension == "overworld",
|
||||
)?),
|
||||
};
|
||||
let info = biomes.get(biomes.id(&format!("minecraft:{}", f[4])));
|
||||
let mut sky = environment.sample(f[1].parse()?, info.sky, info.fog);
|
||||
if dimension == "overworld" {
|
||||
apply_weather(&mut sky, f[2].parse()?, f[3].parse()?);
|
||||
}
|
||||
let v3 = |c: [f32; 3]| format!("[{:?},{:?},{:?}]", c[0], c[1], c[2]);
|
||||
let v4 = |c: [f32; 4]| format!("[{:?},{:?},{:?},{:?}]", c[0], c[1], c[2], c[3]);
|
||||
let mut row = format!("{{\"case\":\"{line}\"");
|
||||
let mut put = |name: &str, value: String| {
|
||||
let _ = write!(row, ",\"minecraft:{name}\":{value}");
|
||||
};
|
||||
put("visual/sky_color", v3(sky.sky_color));
|
||||
put("visual/fog_color", v3(sky.fog_color));
|
||||
put("visual/cloud_color", v4(sky.cloud_color));
|
||||
put("visual/sunrise_sunset_color", v4(sky.sunrise_color));
|
||||
put("visual/sky_light_factor", format!("{:?}", sky.sky_light_factor));
|
||||
put("visual/sky_light_color", v3(sky.sky_light_color));
|
||||
put("visual/block_light_tint", v3(sky.block_light_tint));
|
||||
put("visual/ambient_light_color", v3(sky.ambient_light_color));
|
||||
put("visual/sun_angle", format!("{:?}", sky.sun_angle));
|
||||
put("visual/moon_angle", format!("{:?}", sky.moon_angle));
|
||||
put("visual/star_angle", format!("{:?}", sky.star_angle));
|
||||
put("visual/star_brightness", format!("{:?}", sky.star_brightness));
|
||||
put("gameplay/sky_light_level", format!("{:?}", sky.sky_light_level * 15.0));
|
||||
put("visual/fog_start_distance", format!("{:?}", sky.fog_start));
|
||||
put("visual/fog_end_distance", format!("{:?}", sky.fog_end));
|
||||
out.push_str(&row);
|
||||
out.push_str("}\n");
|
||||
}
|
||||
fs::write(args.get(3).ok_or("missing OUTPUT")?, out)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryDataLoader;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.RegistryLayer;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.repository.ServerPacksSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.world.attribute.*;
|
||||
import net.minecraft.world.clock.*;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import org.joml.Vector3fc;
|
||||
import org.joml.Vector4fc;
|
||||
|
||||
/**
|
||||
* Original oracle: builds the vanilla EnvironmentAttributeSystem (dimension
|
||||
* layer, biome layer for one fixed biome, dimension timelines, weather layers)
|
||||
* from the vanilla data pack and prints every visual/gameplay attribute for
|
||||
* fixture lines "dimension ticks rain thunder biome".
|
||||
*/
|
||||
public final class VanillaEnvironmentOracle {
|
||||
private static String fmt(Object v) {
|
||||
if (v instanceof Vector3fc c) return String.format("[%s,%s,%s]", c.x(), c.y(), c.z());
|
||||
if (v instanceof Vector4fc c) return String.format("[%s,%s,%s,%s]", c.x(), c.y(), c.z(), c.w());
|
||||
if (v instanceof Float f) return f.toString();
|
||||
if (v instanceof Boolean b) return b.toString();
|
||||
if (v instanceof Enum<?> e) return "\"" + e.name() + "\"";
|
||||
return null;
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private static void addBiome(EnvironmentAttributeSystem.Builder b, EnvironmentAttribute attr, Biome biome) {
|
||||
b.addPositionalLayer(attr, (base, pos, w) -> biome.getAttributes().applyModifier(attr, base));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
Path in = Path.of(args[0]), out = Path.of(args[1]);
|
||||
var repo = ServerPacksSource.createVanillaTrustedRepository();
|
||||
repo.reload();
|
||||
repo.setSelected(List.of("vanilla"));
|
||||
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
|
||||
var layers = RegistryLayer.createRegistryAccess();
|
||||
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
|
||||
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
|
||||
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
|
||||
staticTags.forEach(Registry.PendingTags::apply);
|
||||
var dimensions = world.lookupOrThrow(Registries.DIMENSION_TYPE);
|
||||
var biomes = world.lookupOrThrow(Registries.BIOME);
|
||||
try (var w = new PrintWriter(Files.newBufferedWriter(out, StandardCharsets.UTF_8))) {
|
||||
for (String line : Files.readAllLines(in, StandardCharsets.UTF_8)) {
|
||||
String[] f = line.split(" ");
|
||||
DimensionType dim = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.withDefaultNamespace(f[0]))).value();
|
||||
long ticks = Long.parseLong(f[1]);
|
||||
float rain = Float.parseFloat(f[2]), thunder = Float.parseFloat(f[3]);
|
||||
Biome biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.withDefaultNamespace(f[4]))).value();
|
||||
ClockManager clocks = h -> new ClockInstance() {
|
||||
public long totalTicks() { return ticks; }
|
||||
public float partialTick() { return 0.0F; }
|
||||
public float rate() { return 1.0F; }
|
||||
public boolean isPaused() { return false; }
|
||||
};
|
||||
var b = EnvironmentAttributeSystem.builder();
|
||||
b.addConstantLayer(dim.attributes());
|
||||
for (EnvironmentAttribute<?> attr : biome.getAttributes().keySet()) addBiome(b, attr, biome);
|
||||
dim.timelines().forEach(t -> b.addTimelineLayer(t, clocks));
|
||||
if (dim.hasSkyLight() && !dim.hasCeiling()) {
|
||||
WeatherAttributes.addBuiltinLayers(b, new WeatherAttributes.WeatherAccess() {
|
||||
public float rainLevel() { return rain; }
|
||||
public float thunderLevel() { return thunder; }
|
||||
});
|
||||
}
|
||||
var system = b.build();
|
||||
StringBuilder sb = new StringBuilder("{\"case\":\"" + line + "\"");
|
||||
for (var entry : BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.entrySet()) {
|
||||
EnvironmentAttribute<?> attr = entry.getValue();
|
||||
String s = fmt(system.getValue(attr, Vec3.ZERO));
|
||||
if (s != null) sb.append(",\"").append(entry.getKey().identifier()).append("\":").append(s);
|
||||
}
|
||||
w.println(sb.append("}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+91
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare Horizon's environment attributes with the vanilla 26.3 attribute system.
|
||||
|
||||
The Java oracle builds vanilla's `EnvironmentAttributeSystem` from the data pack
|
||||
(dimension attributes, one biome's attributes, the dimension timelines and the
|
||||
weather layers) and prints every visual/gameplay attribute for a grid of
|
||||
dimensions, world times, rain/thunder levels and biomes.
|
||||
`examples/environment_fixture` samples the same cases through Horizon's
|
||||
`Environment::sample` + `apply_weather`; every attribute Horizon computes must
|
||||
agree with vanilla.
|
||||
|
||||
test_environment_render_parity.py [--tolerance EPS]
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
try:
|
||||
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
except ImportError:
|
||||
import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
|
||||
|
||||
def cases(resources):
|
||||
biomes = sorted(p.stem for p in (resources / 'data/minecraft/worldgen/biome').glob('*.json'))
|
||||
out = []
|
||||
for dim in ['overworld', 'overworld_caves', 'the_nether', 'the_end']:
|
||||
for ticks in list(range(0, 48000, 250)) + [23999, 24001, 1234567]:
|
||||
for rain, thunder in [(0, 0), (0.5, 0), (1, 0), (1, 1), (0.7, 0.3)] if dim == 'overworld' else [(0, 0)]:
|
||||
out.append(f'{dim} {ticks} {rain} {thunder} plains')
|
||||
for dim in ['overworld', 'the_nether', 'the_end']:
|
||||
for biome in biomes:
|
||||
for ticks in (0, 6000, 12500, 18000):
|
||||
for rain, thunder in [(0, 0), (1, 0.4)] if dim == 'overworld' else [(0, 0)]:
|
||||
out.append(f'{dim} {ticks} {rain} {thunder} {biome}')
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--tolerance', type=float, default=2e-5)
|
||||
args = parser.parse_args()
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / 'rust-environment-parity'; build.mkdir(parents=True, exist_ok=True)
|
||||
resources = lab.LOCAL / 'horizon-client' / '26.3'
|
||||
inputs = build / 'inputs.txt'; inputs.write_text('\n'.join(cases(resources)) + '\n')
|
||||
classes = build / 'classes'; classes.mkdir(exist_ok=True)
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEnvironmentOracle.java'
|
||||
deps = os.pathsep.join(map(str, libraries))
|
||||
|
||||
def run(command, name):
|
||||
with (build / (name + '.log')).open('w') as log:
|
||||
result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
|
||||
if result.returncode:
|
||||
print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed')
|
||||
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java',
|
||||
'-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.VanillaEnvironmentOracle', inputs, build / 'vanilla.jsonl'], 'vanilla')
|
||||
run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'environment_fixture', '--',
|
||||
resources, inputs, build / 'rust.jsonl'], 'rust')
|
||||
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()]
|
||||
rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()]
|
||||
assert len(vanilla) == len(rust), (len(vanilla), len(rust))
|
||||
bad = {}
|
||||
uncovered = set()
|
||||
for v, r in zip(vanilla, rust):
|
||||
for key, expected in v.items():
|
||||
if key == 'case':
|
||||
continue
|
||||
if key not in r:
|
||||
uncovered.add(key); continue
|
||||
got = r[key]
|
||||
pairs = zip(expected, got) if isinstance(expected, list) else [(expected, got)]
|
||||
if any(abs(a - b) > args.tolerance * (1 + abs(a)) for a, b in pairs):
|
||||
bad.setdefault(key, []).append((v['case'], expected, got))
|
||||
print(f'{len(vanilla)} cases compared')
|
||||
for key, items in sorted(bad.items()):
|
||||
print(f'MISMATCH {key}: {len(items)} cases, e.g. {items[0]}')
|
||||
if uncovered:
|
||||
print('attributes Horizon does not model:', ', '.join(sorted(uncovered)))
|
||||
if bad:
|
||||
sys.exit(f'{len(bad)} attributes differ from vanilla')
|
||||
print('environment parity ok')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user