Merge branch 'main' into night-entities

This commit is contained in:
Ludovic Marie
2026-10-10 10:26:59 +02:00
155 changed files with 18644 additions and 1734 deletions
+74
View File
@@ -0,0 +1,74 @@
"""Shared plumbing for the interaction/inventory differential harnesses
(test_recipe_parity, test_menu_click_parity, test_block_interaction_parity):
compile and run a vanilla Java oracle headlessly, run the matching Rust
example, and report differing lines grouped by a key."""
import json
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
RESOURCES = lab.LOCAL / 'horizon-client' / '26.3'
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
def work_dir(name):
path = lab.LOCAL / name
path.mkdir(parents=True, exist_ok=True)
return path
class Vanilla:
"""Compiles oracles against the pinned server jar and runs them."""
def __init__(self, work):
self.lock, self.jars, self.libraries = base.verify_artifacts()
self.work = work
self.classes = work / 'classes'
self.classes.mkdir(exist_ok=True)
self.deps = os.pathsep.join(map(str, [self.jars['server'], *self.libraries]))
def compile(self, *oracles):
sources = [PARITY / (name + '.java') for name in oracles]
done = subprocess.run(['javac', '--release', str(self.lock['minecraft']['java_major']), '-proc:none',
'-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), '-nowarn', '-Xmaxerrs', '30',
'-cp', self.deps, '-d', str(self.classes), *map(str, sources)], capture_output=True, text=True)
if done.returncode:
print(done.stderr.replace(str(lab.ROOT) + '/', ''))
raise SystemExit('javac failed')
def run(self, oracle, *args, heap='2G'):
subprocess.run(['java', f'-Xmx{heap}', '-cp', str(self.classes) + os.pathsep + self.deps,
'dev.horizonlab.parity.' + oracle, *map(str, args)], check=True)
def cargo_example(package, example, *args, profile=None):
command = ['cargo', 'run', '-q', '-j3']
if profile:
command += ['--profile', profile]
command += ['-p', package, '--example', example, '--', *map(str, args)]
subprocess.run(command, check=True, cwd=lab.ROOT)
def compare(cases, native_path, rust_path, key, describe=None, limit=3):
"""Print differing cases grouped by key(case, native_line); returns the count."""
native = Path(native_path).read_text().split('\n')
rust = Path(rust_path).read_text().split('\n')
if len(native) != len(rust):
print(f'line counts differ: native {len(native)} rust {len(rust)}')
groups = {}
for case, a, b in zip(cases, native, rust):
if a != b:
groups.setdefault(key(case, a), []).append((case, a, b))
describe = describe or (lambda case: case if isinstance(case, str) else json.dumps(case))
total = sum(len(v) for v in groups.values())
for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])):
print(f'{name}: {len(entries)} differing')
for case, a, b in entries[:limit]:
print(f' case {describe(case)}\n native {a}\n rust {b}')
print(f'{len(cases) - total}/{len(cases)} cases match')
return total
View File
+118
View File
@@ -0,0 +1,118 @@
"""Shared plumbing for single-oracle differential harnesses.
A harness supplies a Java oracle (compiled against the pinned client jar and its
libraries), a Rust example probe, and a text input; both programs write one
result line per input line and the outputs must be byte-identical."""
import os
from pathlib import Path
import subprocess
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 run_logged(command, build, name, timeout=900, **kwargs):
with (build / (name + '.log')).open('w') as log:
subprocess.run([str(c) for c in command], cwd=lab.ROOT, check=True, timeout=timeout,
stdout=log, stderr=subprocess.STDOUT, **kwargs)
def compile_oracle(build, oracle_name, jars, libraries, java_major):
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' / (oracle_name + '.java')
classes = build / 'classes'
classes.mkdir(parents=True, exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
run_logged(['javac', '--release', java_major, '-proc:none', '-sourcepath',
lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle],
build, 'compile-java-' + oracle_name)
return classes, dependencies, oracle
def build_probe(build, example):
run_logged(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', example],
build, 'compile-rust-' + example, env=dict(os.environ, CARGO_BUILD_JOBS='3'))
import json
metadata = json.loads(subprocess.check_output(
['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT))
return Path(metadata['target_directory']) / 'debug/examples' / example
def java_run(build, classes, dependencies, main_class, args, name, jvm=()):
run_logged(['java', '-Xmx2g', '-Djava.awt.headless=true', *jvm, '-cp', str(classes) + os.pathsep + dependencies,
'dev.horizonlab.parity.' + main_class, *args], build, name)
def compare(client_out, rust_out, expected_lines):
matched = base.compare(client_out, rust_out)
if matched != expected_lines:
raise AssertionError(f'Incomplete output: {matched} of {expected_lines} lines')
return matched
def differential(name, oracle, probe, make_input, scope, sources=(), expected_lines=None):
"""Compile the oracle and probe, run both on one input and require identical output."""
import platform
lock, jars, libraries = base.verify_artifacts()
libraries = baking.client_libraries()
build = lab.LOCAL / name
build.mkdir(exist_ok=True)
report = build / 'report.json'
report.unlink(missing_ok=True)
oracle_path = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity' / (oracle + '.java')
all_sources = [Path(__file__).resolve(), lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/test_rust_parity.py',
lab.ROOT / 'tools/lab.py', oracle_path, lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock',
lab.ROOT / 'crates/horizon-client/Cargo.toml', lab.ROOT / 'crates/horizon-client/src/lib.rs',
lab.ROOT / f'crates/horizon-client/examples/{probe}.rs', *map(Path, sources)]
tested = base.source_hashes(all_sources)
input_path, units = make_input(build)
input_hash = lab.digest(input_path, 'sha256') if input_path.is_file() else None
classes, dependencies, _ = compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major'])
binary = build_probe(build, probe)
run_logged([binary, input_path, build / 'rust.txt'], build, 'rust')
java_run(build, classes, dependencies, oracle, [input_path, build / 'client.txt'], 'client')
try:
matched = base.compare(build / 'client.txt', build / 'rust.txt')
except AssertionError as error:
raise AssertionError(str(error) + explain(build, str(error))) from None
if expected_lines is not None and matched != expected_lines:
raise AssertionError(f'Incomplete output: {matched} of {expected_lines} lines')
base.ensure_sources_unchanged(all_sources, tested)
if input_hash is not None and input_hash != lab.digest(input_path, 'sha256'):
raise AssertionError('Input fixtures changed')
lab.write_json(report, dict(
schema=1, minecraft=lock['minecraft']['version'], manifest_sha1=lock['minecraft']['manifest_sha1'],
platform=platform.platform(), rustc=subprocess.check_output(['rustc', '--version'], text=True).strip(),
java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], units=units,
sources_sha256=tested, input_sha256=input_hash, client_jar_sha256=lab.digest(jars['client'], 'sha256'),
matched_output_lines=matched, output_sha256=lab.digest(build / 'rust.txt', 'sha256'), scope=scope))
print(f'{units:,} {name} cases match the pinned client ({matched:,} output lines): {report}', flush=True)
return matched
def explain(build, message):
"""Summarise differing sections ("== name" blocks) of multi-case outputs."""
def sections(path):
out, name = {}, None
for line in path.read_text(encoding='utf-8', errors='replace').splitlines():
if line.startswith('== '):
name = line[3:]
out[name] = []
elif name is not None:
out[name].append(line)
return out
left, right = sections(build / 'client.txt'), sections(build / 'rust.txt')
report, count = '', 0
for name in left:
if left[name] != right.get(name):
count += 1
if count <= 25:
case = build / 'cases' / name
text = case.read_text(encoding='utf-8', errors='replace') if case.is_file() else ''
a, b = left[name], right.get(name, [])
diffs = [(x, y) for x, y in zip(a, b) if x != y][:4]
if len(a) != len(b):
diffs.append((f'<{len(a)} lines>', f'<{len(b)} lines>'))
report += f"\n case {name}: {text[:300]!r}\n differences (vanilla, rust): {diffs}"
return f'\n{count} differing cases.' + report
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""Compare the data-driven axe/hoe/shovel block transformers with vanilla.
The Java oracle (VanillaBlockTransformerOracle) evaluates the registry's
BlockStateProviders on a stand-in level; the Rust example
(block_transform_fixture) evaluates horizon_client::block_transform. Cases are
every block state any transformer mentions (plus a random sample of all states)
under each transformer, with a few blocks above and three clicked faces.
"""
import argparse
import random
try:
from . import interaction_lab as lib, lab
except ImportError:
import interaction_lab as lib
import lab
ABOVE = ['minecraft:air|', 'minecraft:cave_air|', 'minecraft:stone|', 'minecraft:water|level=0', 'minecraft:oak_slab|type=bottom,waterlogged=false']
FACES = ['up', 'down', 'north']
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', type=int, default=7)
parser.add_argument('--sample', type=int, default=3000)
parser.add_argument('--limit', type=int, default=4)
args = parser.parse_args()
work = lib.work_dir('block-transformer-parity')
vanilla = lib.Vanilla(work)
vanilla.compile('ParityData', 'VanillaBlockTransformerOracle')
vanilla.run('VanillaBlockTransformerOracle', 'dump', work / 'states.txt')
states = (work / 'states.txt').read_text().splitlines()
mentioned = set()
for path in (lib.RESOURCES / 'data/minecraft/block_transformer').glob('*.json'):
text = path.read_text()
for name in set(__import__('re').findall(r'"minecraft:([a-z_0-9]+)"', text)):
mentioned.add('minecraft:' + name)
tags = set()
for tag in ['turns_into_farmland', 'turns_into_dirt_path', 'air']:
for name in __import__('json').loads((lib.RESOURCES / 'data/minecraft/tags/block' / (tag + '.json')).read_text())['values']:
if not name.startswith('#'):
tags.add(name)
rng = random.Random(args.seed)
chosen = [s for s in states if s.split('|')[0] in mentioned or s.split('|')[0] in tags or 'copper' in s or 'lightning_rod' in s]
chosen += rng.sample(states, args.sample)
cases = []
for transformer in ['axe', 'hoe', 'shovel', 'honeycomb']:
for state in chosen:
for face in FACES:
cases.append('\t'.join([transformer, face, state, rng.choice(ABOVE)]))
(work / 'cases.txt').write_text(''.join(c + '\n' for c in cases))
vanilla.run('VanillaBlockTransformerOracle', work / 'cases.txt', work / 'native.txt')
lib.cargo_example('horizon-client', 'block_transform_fixture', lib.RESOURCES, work / 'cases.txt', work / 'rust.txt')
total = lib.compare(cases, work / 'native.txt', work / 'rust.txt',
lambda case, line: case.split('\t')[0] + ' ' + line.split('\t')[0][:12], None, args.limit)
raise SystemExit(1 if total else 0)
if __name__ == '__main__':
main()
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""Compare cauldron item interactions with vanilla's CauldronInteractions.
The Java oracle (VanillaCauldronOracle) calls the cauldron block's useItemOn
with a recording level and player; the Rust example (cauldron_fixture) runs
horizon_client::cauldron. Every item is used on every cauldron state (empty,
water, lava and powder snow at each level), with water potions, dyed armour,
patterned banners and shulker boxes, in survival and creative, under water or
not, and with a crowded inventory. The result, block writes, sounds, drops and
the final inventory are compared.
"""
import argparse
import json
import random
try:
from . import interaction_lab as lib, lab
except ImportError:
import interaction_lab as lib
import lab
STATES = ['minecraft:cauldron|', 'minecraft:water_cauldron|level=1', 'minecraft:water_cauldron|level=2',
'minecraft:water_cauldron|level=3', 'minecraft:lava_cauldron|', 'minecraft:powder_snow_cauldron|level=1',
'minecraft:powder_snow_cauldron|level=3']
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple',
'blue', 'brown', 'green', 'red', 'black']
def snbt(item, count=1, **components):
body = ','.join('"minecraft:%s":%s' % (k, v) for k, v in sorted(components.items()))
return '{id:"%s",count:%d%s}' % (item, count, ',components:{%s}' % body if body else '')
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', type=int, default=7)
parser.add_argument('--limit', type=int, default=4)
args = parser.parse_args()
work = lib.work_dir('cauldron-parity')
vanilla = lib.Vanilla(work)
vanilla.compile('ParityData', 'VanillaCauldronOracle')
items = json.loads((lib.RESOURCES / 'items.json').read_text())
patterns = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/banner_pattern').glob('*.json'))
rng = random.Random(args.seed)
held = []
for name, info in items.items():
if name == 'minecraft:air':
continue
top = info.get('minecraft:max_stack_size', 64)
held.append(snbt(name, 1))
held.append(snbt(name, rng.randrange(1, top + 1)))
for color in DYES:
for layers in range(0, 4):
body = '[%s]' % ','.join('{pattern:"%s",color:"%s"}' % (rng.choice(patterns), rng.choice(DYES)) for _ in range(layers))
held.append(snbt('minecraft:%s_banner' % color, rng.choice([1, 3]), banner_patterns=body))
held.append(snbt('minecraft:%s_shulker_box' % color, rng.choice([1, 2])))
for item in ['leather_helmet', 'leather_chestplate', 'leather_leggings', 'leather_boots', 'leather_horse_armor', 'wolf_armor']:
held.append(snbt('minecraft:' + item, 1, dyed_color=rng.randrange(1 << 24)))
for potion in ['minecraft:water', 'minecraft:healing', 'minecraft:awkward']:
for item in ['potion', 'splash_potion', 'lingering_potion']:
held.append(snbt('minecraft:' + item, rng.choice([1, 2]), potion_contents='{potion:"%s"}' % potion))
cases = []
filler = [snbt(i, 64) for i in ['minecraft:stone', 'minecraft:dirt', 'minecraft:cobblestone']]
for state in STATES:
for stack in held:
crowded = rng.random() < 0.25
inventory = [[i, rng.choice(filler)] for i in range(1, 36)] if crowded else []
if not crowded and rng.random() < 0.3:
inventory = [[rng.randrange(1, 36), snbt('minecraft:bucket', rng.randrange(1, 16))]]
cases.append({'state': state, 'held': stack, 'creative': rng.random() < 0.3, 'under_water': rng.random() < 0.3,
'inventory': inventory})
(work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases))
vanilla.run('VanillaCauldronOracle', work / 'cases.jsonl', work / 'native.txt')
lib.cargo_example('horizon-client', 'cauldron_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt')
total = lib.compare(cases, work / 'native.txt', work / 'rust.txt',
lambda case, line: case['state'].split('|')[0] + ' ' + line.split('\t')[0],
lambda case: json.dumps(case)[:700], args.limit)
raise SystemExit(1 if total else 0)
if __name__ == '__main__':
main()
+340
View File
@@ -0,0 +1,340 @@
#!/usr/bin/env python3
"""Compare whole generated chunks block-for-block with vanilla.
Vanilla side: VanillaChunkGenerationOracle drives the actual ChunkGenerator
stages (structure starts and references, biomes, terrain with surface and
carvers, then biome decoration with every placed feature and structure piece)
through real WorldGenRegion instances. Horizon side: the chunk_dump example
runs the same stages in the same order. Every block state, quart biome and
block entity (canonical NBT) of each target chunk is compared.
Cases: terrain sites for several seeds across the overworld, the Nether and the
End, plus rectangles around vanilla structure starts found by scanning each
seed (villages, mineshafts, strongholds, ancient cities, trial chambers,
monuments, mansions, ...).
usage: test_chunk_generation_parity.py [--seeds N] [--per-structure K]
[--filter REGEX] [--dimension overworld|the_nether|the_end] [--keep]
"""
import argparse
import json
import os
import random
import re
import subprocess
import sys
import time
from collections import Counter, defaultdict
from pathlib import Path
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
SEEDS = [12345, -7046029254386353131, 987654321987, 4242, -1, 0x5DEECE66D, 20260607, 777]
RESOURCES = lab.LOCAL / 'horizon-client/26.3'
ORACLE = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaChunkGenerationOracle.java'
def build_dir():
path = lab.LOCAL / 'chunk-generation-parity'
path.mkdir(parents=True, exist_ok=True)
return path
class Oracle:
def __init__(self):
self.lock, self.jars, self.libraries = base.verify_artifacts()
self.dependencies = os.pathsep.join(map(str, [self.jars['server'], *self.libraries]))
self.classes = build_dir() / 'classes'
self.classes.mkdir(exist_ok=True)
result = subprocess.run(['javac', '--release', str(self.lock['minecraft']['java_major']), '-proc:none', '-cp', self.dependencies,
'-d', str(self.classes), str(ORACLE)], capture_output=True, text=True)
if result.returncode:
raise SystemExit('javac failed:\n' + result.stderr[-4000:])
def run(self, out, args):
result = subprocess.run(['java', '-Xmx8G', '-cp', str(self.classes) + os.pathsep + self.dependencies,
'dev.horizonlab.parity.VanillaChunkGenerationOracle', *map(str, [args[0], out, *args[1:]])],
capture_output=True, text=True, env=dict(os.environ))
if result.returncode:
lines = [l for l in (result.stdout + result.stderr).splitlines() if 'Exception' in l or 'Caused' in l or '\tat ' in l]
raise SystemExit('oracle failed: ' + ' | '.join(lines[:10]))
def rust_binary():
subprocess.run(['cargo', 'build', '--release', '-q', '-p', 'horizon-world', '--example', 'chunk_dump'], check=True, cwd=lab.ROOT)
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
return Path(metadata['target_directory']) / 'release/examples/chunk_dump'
def run_rust(binary, out, seed, dimension, rects, scan=False):
env = dict(os.environ)
if scan:
env['HORIZON_SCAN'] = '1'
with open(out, 'w') as handle:
result = subprocess.run([str(binary), str(RESOURCES), str(seed), dimension, *rects], stdout=handle, stderr=subprocess.PIPE, text=True, env=env, cwd=lab.ROOT)
if result.returncode:
raise SystemExit('chunk_dump failed: ' + result.stderr[-2000:])
return result.stderr
def parse(path):
chunks, current = {}, None
for line in Path(path).read_text().splitlines():
if line.startswith('chunk '):
_, x, z = line.split()
current = (int(x), int(z))
chunks[current] = {'q': {}, 'y': {}, 'be': {}}
elif line.startswith('q '):
_, q, row = line.split(' ', 2)
chunks[current]['q'][int(q)] = row
elif line.startswith('y '):
_, y, row = line.split(' ', 2)
chunks[current]['y'][int(y)] = row
elif line.startswith('be '):
head, *forms = line.split('\t')
parts = head.split(' ')
chunks[current]['be'][(int(parts[1]), int(parts[2]), int(parts[3]))] = forms
return chunks
def parse_nbt(text, i=0):
"""Canonical NBT text -> Python values (typed scalars as (type, text) tuples)."""
c = text[i]
if c == '{':
i += 1
value = {}
while text[i] != '}':
j = text.index('=', i)
key = text[i:j]
value[key], i = parse_nbt(text, j + 1)
i += 1 # comma
return value, i + 1
if c == '[':
i += 1
items = []
while text[i] != ']':
item, i = parse_nbt(text, i)
items.append(item)
i += 1
return items, i + 1
if c == '"':
i += 1
out = []
while text[i] != '"':
if text[i] == '\\':
i += 1
out.append(text[i])
i += 1
return ('str', ''.join(out)), i + 1
if c in 'BIL' and text[i + 1] == '[':
j = text.index(']', i)
return (c, text[i + 2:j]), j + 1
j = i + 1
while j < len(text) and text[j] not in ',}]':
j += 1
return (c, text[i + 1:j]), j
def nbt_matches(vanilla, rust, default):
"""Horizon stores the placed data only; vanilla saves defaults too. Every key
Horizon sets must match, and every other vanilla key must be the fresh default."""
if isinstance(vanilla, dict) and isinstance(rust, dict):
default = default if isinstance(default, dict) else {}
if 'LootTableSeed' in rust and 'LootTable' not in rust:
rust = {k: v for k, v in rust.items() if k != 'LootTableSeed'} # vanilla saves the seed only with a table
for key, value in vanilla.items():
if key in ('x', 'y', 'z') or (key == 'components' and value == {}):
continue
if key in rust:
if not nbt_matches(value, rust[key], default.get(key)):
return False
elif value != default.get(key):
return False
return all(key in vanilla or key in ('x', 'y', 'z') or nbt_matches(default.get(key), rust[key], None) or (key, rust[key]) == VAULT_REWARD for key in rust)
if isinstance(vanilla, list) and isinstance(rust, list):
return len(vanilla) == len(rust) and all(nbt_matches(a, b, None) for a, b in zip(vanilla, rust))
if isinstance(vanilla, tuple) and isinstance(rust, tuple) and vanilla[0] in 'bsil' and rust[0] in 'bsil':
# Structure templates keep their stored integer width; vanilla re-saves block entities with its own.
return vanilla[1] == rust[1]
return vanilla == rust
def entity_matches(vanilla, rust):
if vanilla is None:
return False
if rust is None:
# A DUMMY pending entry in a proto chunk: vanilla creates the default block entity on demand.
return nbt_matches(parse_nbt(vanilla[0])[0], {}, parse_nbt(vanilla[1])[0])
return nbt_matches(parse_nbt(vanilla[0])[0], parse_nbt(rust[0])[0], parse_nbt(vanilla[1])[0])
def state_names():
facts = json.loads((RESOURCES / 'facts.json').read_text())
return [s[3].removeprefix('Block{').replace('}', '', 1) for s in facts['states']]
AIR = '0'
# A vault's config omits its default reward table when saved by vanilla; templates spell it out.
VAULT_REWARD = ('loot_table', ('str', 'minecraft:chests/trial_chambers/reward'))
def compare(vanilla, rust, names, label, limit=6, quiet=False):
"""Returns (differing chunks, differing blocks, differing biome cells, differing block entities)."""
chunks = blocks = biomes = entities = 0
for pos in sorted(vanilla):
a, b = vanilla[pos], rust.get(pos)
if b is None:
print(f' {label} chunk {pos}: missing from Horizon output')
chunks += 1
continue
block_diffs, biome_diffs, entity_diffs = [], [], []
for y in sorted(a['y']):
ra, rb = a['y'][y], b['y'].get(y)
if ra == rb:
continue
if rb is None:
# Above the noise height (Nether roof, End sky) Horizon keeps no section; vanilla's is all air.
if set(ra.split(' ')) != {AIR}:
block_diffs.append((pos[0] * 16, y, pos[1] * 16, 'non-air section', 'section missing'))
continue
for i, (u, v) in enumerate(zip(ra.split(' '), rb.split(' '))):
if u != v:
block_diffs.append((pos[0] * 16 + i % 16, y, pos[1] * 16 + i // 16, names[int(u)], names[int(v)]))
for q in sorted(a['q']):
if q not in b['q']:
continue # biomes of sections Horizon does not generate (above the noise height)
if a['q'][q] != b['q'].get(q):
for i, (u, v) in enumerate(zip(a['q'][q].split(' '), b['q'].get(q, '').split(' '))):
if u != v:
biome_diffs.append((pos[0] * 4 + i % 4, q, pos[1] * 4 + i // 4, u, v))
for key in sorted(set(a['be']) | set(b['be'])):
if not entity_matches(a['be'].get(key), b['be'].get(key)):
entity_diffs.append((key, a['be'].get(key, [None])[0], (b['be'].get(key) or [None])[0]))
if block_diffs or biome_diffs or entity_diffs:
chunks += 1
blocks += len(block_diffs)
biomes += len(biome_diffs)
entities += len(entity_diffs)
if quiet:
continue
print(f' {label} chunk {pos}: {len(block_diffs)} blocks, {len(biome_diffs)} biome cells, {len(entity_diffs)} block entities')
for d in block_diffs[:limit]:
print(f' block {d[0]} {d[1]} {d[2]}: vanilla {d[3]} / horizon {d[4]}')
for d in biome_diffs[:2]:
print(f' biome quart {d[0]} {d[1]} {d[2]}: vanilla {d[3]} / horizon {d[4]}')
for d in entity_diffs[:3]:
print(f' block entity {d[0]}: vanilla {d[1]} / horizon {d[2]}')
return chunks, blocks, biomes, entities
def scan(oracle, binary, seed, dimension, radius):
out = build_dir() / f'scan-{dimension}-{seed}.txt'
oracle.run(out, ['scan', seed, dimension, -radius, -radius, radius, radius])
starts = []
for line in out.read_text().splitlines():
t = line.split()
if t and t[0] == 'start':
starts.append((t[1], int(t[2]), int(t[3]), tuple(map(int, t[4:10]))))
return starts
def pick_structures(starts, per_kind, rng):
by_kind = defaultdict(list)
for s in starts:
by_kind[s[0]].append(s)
picked = []
for kind, items in sorted(by_kind.items()):
items.sort(key=lambda s: abs(s[1]) + abs(s[2]))
# Nearest first, then random ones, so that variants (village types) differ.
chosen = items[:1] + rng.sample(items[1:], min(per_kind - 1, len(items) - 1))
picked.extend(chosen[:per_kind])
return picked
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seeds', type=int, default=3)
parser.add_argument('--per-structure', type=int, default=2)
parser.add_argument('--sites', type=int, default=6, help='terrain sites per overworld seed')
parser.add_argument('--radius', type=int, default=1, help='chunk radius around each site')
parser.add_argument('--scan-radius', type=int, default=180)
parser.add_argument('--limit', type=int, default=6, help='block differences shown per chunk')
parser.add_argument('--summary', action='store_true', help='one line per differing site')
parser.add_argument('--rect', action='append', help='compare only this x0,z0,x1,z1 chunk rectangle (repeatable)')
parser.add_argument('--filter', help='regex over structure names')
parser.add_argument('--dimension', action='append')
parser.add_argument('--phase', choices=['terrain', 'structures', 'full'], default='full', help='stop before features, or run structure pieces only')
parser.add_argument('--terrain-only', action='store_true', help='skip the structure sites')
parser.add_argument('--structures-only', action='store_true')
args = parser.parse_args()
os.environ['HORIZON_PHASE'] = args.phase
dimensions = args.dimension or ['overworld', 'the_nether', 'the_end']
oracle = Oracle()
binary = rust_binary()
names = state_names()
build = build_dir()
totals = Counter()
biome_seen = set()
structure_seen = Counter()
started = time.time()
for seed in SEEDS[:args.seeds]:
rng = random.Random(seed)
for dimension in dimensions:
rects, labels = [], []
if args.rect:
rects, labels = list(args.rect), [f'rect {r}' for r in args.rect]
r = args.radius
if not args.structures_only and not args.rect:
spread = {'overworld': 5000, 'the_nether': 1500, 'the_end': 1800}[dimension]
sites = [(0, 0)] + [(rng.randint(-spread, spread) // 16, rng.randint(-spread, spread) // 16) for _ in range(args.sites if dimension == 'overworld' else 2)]
for cx, cz in sites:
rects.append(f'{cx - r},{cz - r},{cx + r},{cz + r}')
labels.append(f'terrain {cx},{cz}')
if not args.terrain_only and not args.rect:
starts = scan(oracle, binary, seed, dimension, args.scan_radius if dimension == 'overworld' else 80)
for kind, cx, cz, box in pick_structures(starts, args.per_structure, rng):
if args.filter and not re.search(args.filter, kind):
continue
rects.append(f'{cx - r},{cz - r},{cx + r},{cz + r}')
labels.append(f'{kind} {cx},{cz}')
structure_seen[kind] += 1
if not rects:
continue
tag = f'{dimension}-{seed}-{args.phase}' + ('-iso' if os.environ.get('HORIZON_ISOLATED') else '') + ('-rect' if args.rect else '')
vanilla_path, rust_path = build / f'vanilla-{tag}.txt', build / f'rust-{tag}.txt'
t0 = time.time()
if not (os.environ.get('REUSE_VANILLA') and vanilla_path.exists()):
oracle.run(vanilla_path, ['dump', seed, dimension, *rects])
t1 = time.time()
stderr = run_rust(binary, rust_path, seed, dimension, rects)
t2 = time.time()
vanilla, rust = parse(vanilla_path), parse(rust_path)
for line in stderr.splitlines()[:5]:
print(' horizon:', line)
counts = [0, 0, 0, 0]
for rect, label in zip(rects, labels):
x0, z0, x1, z1 = map(int, rect.split(','))
part = {k: v for k, v in vanilla.items() if x0 <= k[0] <= x1 and z0 <= k[1] <= z1}
one = compare(part, rust, names, f'{tag} {label}', limit=args.limit, quiet=args.summary)
if one[0]:
print(f'{tag} {label}: {one[0]} chunks differ ({one[1]} blocks, {one[2]} biome cells, {one[3]} block entities)')
counts = [a + b for a, b in zip(counts, one)]
totals.update(dict(zip(['chunks', 'blocks', 'biomes', 'entities'], counts)))
totals['compared'] += len(vanilla)
for chunk in vanilla.values():
for row in chunk['q'].values():
biome_seen.update(row)
print(f'{tag}: {len(rects)} sites, {len(vanilla)} chunks, differing chunks {counts[0]} (blocks {counts[1]}, biome cells {counts[2]}, block entities {counts[3]}); vanilla {t1 - t0:.0f}s, horizon {t2 - t1:.0f}s', flush=True)
print(f'Compared {totals["compared"]} chunks across {len(biome_seen)} biomes and {sum(structure_seen.values())} structure sites in {time.time() - started:.0f}s')
print('structure sites:', dict(sorted(structure_seen.items())))
print(f'Differences: {totals["chunks"]} chunks, {totals["blocks"]} blocks, {totals["biomes"]} biome cells, {totals["entities"]} block entities')
if totals['chunks']:
sys.exit(1)
if __name__ == '__main__':
main()
+296
View File
@@ -0,0 +1,296 @@
#!/usr/bin/env python3
"""Compare entity model geometry and setupAnim poses with the vanilla 26.3 client.
The Java oracle bakes each vanilla model layer, builds the model's own render
state class with the generated walk/age/head/attack inputs (plus per-species
state fields), runs the real `setupAnim` and writes every part's pose.
`examples/entity_anim_fixture` replays the same inputs through Horizon's
`mobs::anim::setup` and the loaded model tree; the two must agree on every part
pose and on the baked polygon count and vertex sums.
test_entity_model_parity.py [--filter SUBSTRING] [--detail LAYER] [--tolerance EPS]
"""
import argparse
import json
import math
import os
from pathlib import Path
import random
import re
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
CLIENT = lab.LOCAL / 'minecraft' / '26.3' / 'sources' / 'client' / 'net' / 'minecraft' / 'client'
# Models that no renderer builds with a plain `new Model(context.bakeLayer(CONSTANT))`.
EXTRAS = [
('minecraft:zombie#main', 'ZombieModel'), ('minecraft:zombie_baby#main', 'BabyZombieModel'),
('minecraft:husk#main', 'ZombieModel'), ('minecraft:husk_baby#main', 'BabyZombieModel'),
('minecraft:zombie_villager#main', 'ZombieVillagerModel'),
('minecraft:zombie_villager_baby#main', 'BabyZombieVillagerModel'),
('minecraft:zombified_piglin#main', 'AdultZombifiedPiglinModel'),
('minecraft:zombified_piglin_baby#main', 'BabyZombifiedPiglinModel'),
('minecraft:skeleton#main', 'SkeletonModel'), ('minecraft:stray#main', 'SkeletonModel'),
('minecraft:wither_skeleton#main', 'SkeletonModel'),
('minecraft:spider#main', 'SpiderModel'), ('minecraft:cave_spider#main', 'SpiderModel'),
('minecraft:enderman#main', 'EndermanModel'), ('minecraft:endermite#main', 'EndermiteModel'),
('minecraft:piglin#main', 'AdultPiglinModel'), ('minecraft:piglin_brute#main', 'AdultPiglinModel'),
('minecraft:piglin_baby#main', 'BabyPiglinModel'),
('minecraft:hoglin#main', 'HoglinModel'), ('minecraft:zoglin#main', 'HoglinModel'),
('minecraft:hoglin_baby#main', 'BabyHoglinModel'), ('minecraft:zoglin_baby#main', 'BabyHoglinModel'),
('minecraft:guardian#main', 'GuardianModel'), ('minecraft:elder_guardian#main', 'GuardianModel'),
('minecraft:evoker#main', 'IllagerModel'), ('minecraft:illusioner#main', 'IllagerModel'),
('minecraft:pillager#main', 'IllagerModel'), ('minecraft:vindicator#main', 'IllagerModel'),
('minecraft:llama#main', 'LlamaModel'), ('minecraft:trader_llama#main', 'LlamaModel'),
('minecraft:llama_baby#main', 'BabyLlamaModel'), ('minecraft:trader_llama_baby#main', 'BabyLlamaModel'),
('minecraft:donkey#main', 'DonkeyModel'), ('minecraft:mule#main', 'DonkeyModel'),
('minecraft:donkey_baby#main', 'BabyDonkeyModel'), ('minecraft:mule_baby#main', 'BabyDonkeyModel'),
('minecraft:skeleton_horse#main', 'HorseModel'), ('minecraft:zombie_horse#main', 'HorseModel'),
('minecraft:skeleton_horse_baby#main', 'BabyHorseModel'), ('minecraft:zombie_horse_baby#main', 'BabyHorseModel'),
('minecraft:cave_spider#main', 'SpiderModel'),
('minecraft:stray#main', 'SkeletonModel'),
]
# Layers a renderer reuses for another entity under a different constant.
SKIP_LAYERS = re.compile(r'(banner|bell|book|skull|head|chest|shulker_box|boat|cushion|conduit|leash|arrow|trident|'
r'shield|elytra|spin_attack|ears|cape|decorated_pot|minecart|wind_charge|evoker_fangs|'
r'llama_spit|shulker_bullet|bee_stinger|end_crystal|armor_stand|copper_golem|#(helmet|chestplate|leggings|'
r'boots|outer|armor|decor|saddle|collar|wool|wool_undercoat|eyes|wind|inner|pattern|tendrils|'
r'heart|bioluminescent|pulsating_spots|water_patch|flag|cage|shell)$)')
def layer_constant(name):
"""minecraft:cow_baby#main -> constant COW_BABY (the main layer of a model)."""
return name.split(':')[1].split('#')[0].upper()
def renderer_pairs():
pairs = {}
pattern = re.compile(r'new (\w+)\(\s*(?:context|this\.context|\w*)\.bakeLayer\(ModelLayers\.(\w+)\)')
for path in sorted((CLIENT / 'renderer').rglob('*.java')):
for match in pattern.finditer(path.read_text()):
pairs[match.group(2)] = match.group(1)
return pairs
def layers(models):
chosen = {}
pairs = renderer_pairs()
for key in models:
if not key.endswith('#main') or SKIP_LAYERS.search(key):
continue
constant = layer_constant(key)
if constant in pairs:
chosen[key] = pairs[constant]
for key, cls in EXTRAS:
if key in models:
chosen[key] = cls
return chosen
def cases(layer):
rng = random.Random(0x414e494d + sum(map(ord, layer)))
baby = '_baby#' in layer
base_cases = [
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
(1.0, 0.5, 10.0, 0.0, 0.0, 0.0),
(3.7, 0.6, 57.3, 20.0, -15.0, 0.0),
(12.25, 1.0, 123.5, -35.0, 40.0, 0.0),
(7.5, 0.3, 33.3, 5.0, 5.0, 0.35),
(2.0, 0.0, 77.7, 45.0, -60.0, 0.8),
]
for _ in range(14):
base_cases.append((rng.uniform(0, 30), rng.uniform(0, 1), rng.uniform(0, 400),
rng.uniform(-50, 50), rng.uniform(-70, 70),
rng.choice([0.0, rng.uniform(0.01, 0.99)])))
cases_out = []
for pos, speed, age, y, x, attack in base_cases:
cases_out.append({'walkAnimationPos': pos, 'walkAnimationSpeed': speed, 'ageInTicks': age,
'yRot': y, 'xRot': x, 'swingAnimation': attack, 'isBaby': baby, 'ageScale': 0.5 if baby else 1.0,
'entityId': 7, 'yHeadRot': y, 'yBodyRot': 0.0})
name = layer.split(':')[1].split('#')[0].removesuffix('_baby')
cases_out = [{**c, **DEFAULTS.get(name, {})} for c in cases_out]
yield from cases_out
yield from species_cases(layer, cases_out)
T, F = True, False
FOX = [{'isCrouching': T, 'crouchAmount': 0.8}, {'isSleeping': T}, {'isSitting': T}, {'isPouncing': T, 'crouchAmount': 0.6},
{'isFaceplanted': T}, {'headRollAngle': 0.3}, {'isCrouching': T, 'isPouncing': T, 'crouchAmount': 0.4}]
ILLAGER = [{'armPose': pose, 'maxCrossbowChargeDuration': 25, 'ticksUsingItem': 10.0}
for pose in ['NEUTRAL', 'CROSSED', 'ATTACKING', 'SPELLCASTING', 'BOW_AND_ARROW', 'CROSSBOW_HOLD',
'CROSSBOW_CHARGE', 'CELEBRATING']] + [{'isRiding': T, 'armPose': 'CROSSED'}]
FELINE = [{'isCrouching': T}, {'isSprinting': T}, {'isSitting': T}, {'lieDownAmount': 0.7, 'lieDownAmountTail': 0.5},
{'relaxStateOneAmount': 0.6}, {'isSitting': T, 'lieDownAmount': 1.0, 'lieDownAmountTail': 0.2}]
ZOMBIE = [{'isAggressive': T}, {'isCrouching': T}, {'isPassenger': T}, {'isAggressive': T, 'isPassenger': T, 'isCrouching': T}]
SKELETON = ZOMBIE + [{'isAggressive': T, 'isHoldingBow': T, 'rightArmPose': 'BOW_AND_ARROW'}, {'isHoldingBow': T},
{'isAggressive': T, 'isHoldingBow': T, 'rightArmPose': 'BOW_AND_ARROW', 'isCrouching': T}]
PIGLIN = [{'armPose': pose, 'maxCrossbowChageDuration': 25.0, 'ticksUsingItem': 12.0}
for pose in ['DEFAULT', 'DANCING', 'ATTACKING_WITH_MELEE_WEAPON', 'CROSSBOW_HOLD', 'CROSSBOW_CHARGE', 'ADMIRING_ITEM']]
EQUINE = [{'eatAnimation': 0.6}, {'standAnimation': 0.5}, {'eatAnimation': 0.3, 'standAnimation': 0.4, 'feedingAnimation': 0.7},
{'isInWater': T}, {'standAnimation': 1.0, 'eatAnimation': 1.0}]
WATER = [{'isInWater': T}, {'isInWater': F}]
SPECIES = {
'horse': EQUINE, 'donkey': EQUINE + [{'hasChest': T}], 'mule': EQUINE + [{'hasChest': T}], 'zombie_horse': EQUINE, 'skeleton_horse': EQUINE,
'iron_golem': [{'attackTicksRemaining': 7.0}, {'offerFlowerTick': 30}, {'attackTicksRemaining': 0.0, 'offerFlowerTick': 0}],
'hoglin': [{'attackAnimationRemainingTicks': t} for t in (3, 7, 10)],
'zoglin': [{'attackAnimationRemainingTicks': t} for t in (3, 7, 10)],
'ravager': [{'stunnedTicksRemaining': 20.0}, {'attackTicksRemaining': 8.0}, {'attackTicksRemaining': 3.0},
{'roarAnimation': 0.5}],
'vex': [{'isCharging': T}, {'isCharging': F}],
'squid': [{'tentacleAngle': 0.7}], 'glow_squid': [{'tentacleAngle': 1.2}],
'dolphin': [{'isMoving': T}, {'isMoving': F}],
'cod': WATER, 'salmon': WATER, 'tropical_fish_small': WATER,
'allay': [{'isDancing': T, 'isSpinning': T, 'spinningProgress': 0.6}, {'isDancing': T, 'isSpinning': F, 'spinningProgress': 0.2},
{'holdingAnimationProgress': 0.8}, {'holdingAnimationProgress': 1.0}],
'camel': [{'sitAnimationState': 2}, {'sitPoseAnimationState': 3}, {'sitUpAnimationState': 1}, {'idleAnimationState': 4},
{'dashAnimationState': 2}, {'jumpCooldown': 20.0}],
'chicken': [{'flap': 2.0, 'flapSpeed': 0.7}, {'flap': 5.3, 'flapSpeed': 1.0}],
'wolf': [{'isSitting': T}, {'isAngry': T, 'tailAngle': 1.5393804}, {'shakeAnim': 0.9}, {'interest': 0.6},
{'isSitting': T, 'shakeAnim': 0.5, 'interest': 0.3}],
'zombie': ZOMBIE, 'husk': ZOMBIE, 'drowned': ZOMBIE, 'zombie_villager': ZOMBIE, 'zombified_piglin': ZOMBIE, 'giant': ZOMBIE,
'skeleton': SKELETON, 'stray': SKELETON, 'wither_skeleton': SKELETON, 'bogged': SKELETON,
'piglin': PIGLIN, 'piglin_brute': PIGLIN,
'cat': FELINE, 'ocelot': FELINE,
'creaking': [{'canMove': F}, {'attackAnimationState': 2}, {'invulnerabilityAnimationState': 3}, {'deathAnimationState': 1}],
'evoker': ILLAGER, 'pillager': ILLAGER, 'vindicator': ILLAGER,
'sheep': [{'eatTick': t} for t in (2, 10, 36, 39)],
'guardian': [{'tailAnimation': 4.0, 'spikesAnimation': 0.3}, {'tailAnimation': 0.0, 'spikesAnimation': 0.0}],
'elder_guardian': [{'tailAnimation': 4.0, 'spikesAnimation': 0.3}],
'shulker': [{'peekAmount': v} for v in (0.0, 0.2, 0.5, 1.0)],
'witch': [{'isHoldingItem': T}, {'isHoldingItem': F}],
'goat': [{'hasLeftHorn': T, 'hasRightHorn': T}, {'hasLeftHorn': F, 'hasRightHorn': T, 'rammingXHeadRot': 0.6},
{'hasLeftHorn': T, 'hasRightHorn': F}],
'polar_bear': [{'standScale': 0.0}, {'standScale': 0.5}, {'standScale': 1.0}],
'panda': [{'isUnhappy': T}, {'isSneezing': T, 'sneezeTime': 5}, {'isSneezing': T, 'sneezeTime': 16},
{'sitAmount': 0.6, 'isEating': T}, {'sitAmount': 1.0, 'isScared': T}, {'sitAmount': 0.3},
{'lieOnBackAmount': 0.5}, {'rollAmount': 0.7}],
'llama': [{'hasChest': T}, {'hasChest': F}],
'trader_llama': [{'hasChest': T}, {'hasChest': F}],
'turtle': [{'isOnLand': T}, {'isOnLand': T, 'isLayingEgg': T}, {'isOnLand': F, 'hasEgg': T}, {'isOnLand': T, 'hasEgg': T}],
'strider': [{'isRidden': T}, {'isRidden': F}],
'parrot': [{'pose': pose, 'flapAngle': 0.4} for pose in ['STANDING', 'FLYING', 'ON_SHOULDER', 'SITTING', 'PARTY']],
'bee': [{'hasStinger': T}, {'hasStinger': F, 'isOnGround': T}, {'isAngry': T}, {'rollAmount': 0.6, 'isAngry': T},
{'isOnGround': T, 'hasStinger': T}],
'bat': [{'isResting': T, 'restAnimationState': 3}, {'flyAnimationState': 2}, {'isResting': F, 'flyAnimationState': 0}],
'armadillo': [{'isHidingInShell': T}, {'isHidingInShell': T, 'rollUpAnimationState': 2},
{'rollOutAnimationState': 4}, {'peekAnimationState': 1}],
'axolotl': [{'playingDeadFactor': 0.0, 'inWaterFactor': 1.0, 'onGroundFactor': 0.0, 'movingFactor': 1.0},
{'inWaterFactor': 1.0, 'movingFactor': 0.0}, {'onGroundFactor': 1.0, 'movingFactor': 1.0},
{'onGroundFactor': 1.0, 'movingFactor': 0.0}, {'inWaterFactor': 0.5, 'onGroundFactor': 0.5, 'movingFactor': 0.5},
{'playingDeadFactor': 1.0, 'inWaterFactor': 1.0},
{'walkAnimationState': 1}, {'swimAnimation': 2}, {'idleOnGroundAnimationState': 3},
{'idleUnderWaterAnimationState': 2}, {'idleUnderWaterOnGroundAnimationState': 1}, {'playDeadAnimationState': 4}],
'frog': [{'isSwimming': T}, {'isSwimming': F}, {'jumpAnimationState': 2}, {'croakAnimationState': 1},
{'tongueAnimationState': 3}, {'swimIdleAnimationState': 2, 'isSwimming': T}],
'rabbit': [{'hopAnimationState': 2}, {'idleHeadTiltAnimationState': 1}],
'fox': FOX,
}
# Render-state defaults that are not zero/false in vanilla.
DEFAULTS = {'creaking': {'canMove': T}, 'wolf': {'tailAngle': 0.6283185307179586}, 'axolotl': {'inWaterFactor': 1.0}, 'bee': {'hasStinger': T}, 'sheep': {'eatTick': 0},
'goat': {'hasLeftHorn': T, 'hasRightHorn': T}, 'parrot': {'pose': 'STANDING'},
'phantom': {'flapOffset': 21.0}, 'guardian': {'tailAnimation': 1.3, 'spikesAnimation': 1.0},
'elder_guardian': {'tailAnimation': 1.3, 'spikesAnimation': 1.0}}
def species_cases(layer, base_cases):
name = layer.split(':')[1].split('#')[0].removesuffix('_baby')
for extra in SPECIES.get(name, []):
for index in (2, 3, 6):
yield {**base_cases[index], **extra}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--filter', default='')
parser.add_argument('--detail', default='')
parser.add_argument('--tolerance', type=float, default=5e-7)
args = parser.parse_args()
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
build = lab.LOCAL / 'rust-entity-model-parity'; build.mkdir(parents=True, exist_ok=True)
resources = lab.LOCAL / 'horizon-client' / '26.3'
models = json.loads((resources / 'entity-models.json').read_text())
chosen = {k: v for k, v in layers(models).items() if args.filter in k}
extra_cases = json.loads((Path(__file__).with_suffix('.cases.json')).read_text()) \
if Path(__file__).with_suffix('.cases.json').exists() else {}
lines = []
for layer, cls in sorted(chosen.items()):
for case in cases(layer):
lines.append(f'{layer} {cls}|{json.dumps(case)}')
for case in extra_cases.get(layer.split(':')[1].split('#')[0], []):
lines.append(f'{layer} {cls}|{json.dumps(case)}')
inputs = build / 'inputs.txt'; inputs.write_text('\n'.join(lines) + '\n')
classes = build / 'classes'; classes.mkdir(exist_ok=True)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java'
dependencies = os.pathsep.join(map(str, [jars['client'], *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', '-cp', dependencies, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaEntityAnimOracle',
inputs, build / 'vanilla.jsonl', jars['client']], 'vanilla')
run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'entity_anim_fixture', '--',
resources, build / 'vanilla.jsonl', 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))
errors, skipped, mismatched, checked = {}, set(), {}, 0
for v, r in zip(vanilla, rust):
layer = v['layer']
if 'error' in v:
errors[layer] = v['error']; continue
if 'skip' in r:
skipped.add(layer); continue
checked += 1
bad = []
for path, expected in v['parts'].items():
got = r['parts'].get(path)
if got is None:
bad.append((path, 'missing in Horizon')); continue
names = ['x', 'y', 'z', 'xRot', 'yRot', 'zRot', 'xScale', 'yScale', 'zScale', 'visible', 'polys', 'vsum']
for i, (a, b) in enumerate(zip(expected, got)):
if i == 11 and abs(a - b) <= 1e-3 * max(1, abs(a)):
continue
if i == 9:
a, b = bool(a), bool(b)
if a != b:
bad.append((path, f'visible {a} != {b}'))
continue
if abs(a - b) > args.tolerance * (1.0 + abs(a)):
bad.append((path, f'{names[i]} {a!r} != {b!r}'))
for path in r['parts']:
if path not in v['parts']:
bad.append((path, 'extra in Horizon'))
if bad:
mismatched.setdefault(layer, []).append((v['case'], bad))
print(f'{checked} cases compared over {len(chosen) - len(skipped) - len(errors)} layers')
if errors:
print('oracle errors:'); [print(' ', k, v) for k, v in sorted(errors.items())]
if skipped:
print('layers without a Horizon species:', ', '.join(sorted(skipped)))
for layer, items in sorted(mismatched.items()):
parts = {}
for case, bad in items:
for path, why in bad:
parts.setdefault(path, (why, case))
total = sum(1 for x in vanilla if x['layer'] == layer)
print(f'MISMATCH {layer}: {len(items)}/{total} cases, {len(parts)} parts')
detailed = args.detail == layer
for path, (why, case) in list(parts.items())[:(10 ** 6 if detailed else 4)]:
print(f' {path or "<root>"}: {why}' + (f' case={json.dumps(case)}' if detailed else ''))
if mismatched or errors:
sys.exit(f'{len(mismatched)} layers differ from vanilla')
print('entity model parity ok')
if __name__ == '__main__':
main()
+97
View File
@@ -0,0 +1,97 @@
#!/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', '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')
own = {'the_nether': {'nether_wastes', 'soul_sand_valley', 'crimson_forest', 'warped_forest', 'basalt_deltas'},
'the_end': {'the_end', 'small_end_islands', 'end_midlands', 'end_highlands', 'end_barrens'}}
for dim in ['overworld', 'the_nether', 'the_end']:
for biome in biomes:
if dim in own and biome not in own[dim]:
continue
if dim == 'overworld' and any(biome in b for b in own.values()):
continue
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()
+164
View File
@@ -0,0 +1,164 @@
#!/usr/bin/env python3
"""Compare the game loop and input handling with the pinned client: the
DeltaTracker.Timer, ServerTickRateManager (freeze, step, sprint), Window
scale computation, FramerateLimitTracker decisions, MouseHandler (relative
and absolute motion, sensitivity curve, cinematic smoothing, inversion,
scroll accumulation and discrete scrolling), Entity.turn and ToggleKeyMapping,
all driven with identical synthetic input and time sequences."""
import json
import math
import random
import struct
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
def fbits(v):
return struct.pack('>f', v).hex()
def dbits(v):
return struct.pack('>d', v).hex()
def timer_cases(rng):
for n in range(700):
tps = rng.choice([20.0, 20.0, 10.0, 60.0, 1.0, 144.0])
start = rng.choice([0, 0, 1234, 10**9])
now = start
ops = []
for _ in range(rng.randrange(1, 40)):
kind = rng.choice(['adv', 'adv', 'adv', 'real', 'pause', 'frozen'])
if kind in ('adv', 'real'):
now += rng.choice([0, 1, 2, 7, 16, 17, 33, 49, 50, 51, 99, 100, 101, 250, 999, 5000, 70000])
if rng.random() < 0.03:
now -= rng.randrange(0, 30)
if kind == 'adv':
mspt = rng.choice([None, None, None, 50.0, 25.0, 100.0, 500.0, 1000.0, 0.5, 5.0, 0.1])
ops.append(['adv', now, None if mspt is None else fbits(mspt)])
elif kind == 'real':
ops.append(['real', now])
else:
ops.append([kind, rng.random() < 0.5])
yield dict(t='timer', tps=fbits(tps), start=start, ops=ops)
def rate_cases(rng):
rates = [20.0, 1.0, 0.5, 0.0, -3.0, 100.0, 10000.0, 3.3, 1e-3, 33.333, 7.0, float('nan'), float('inf'), 59.99]
for n in range(500):
ops = []
clock = 0
for _ in range(rng.randrange(1, 40)):
kind = rng.choice(['rate', 'freeze', 'step', 'stopstep', 'sprint', 'check', 'check', 'check', 'end', 'stopsprint',
'tick', 'tick', 'tick'])
if kind == 'rate':
ops.append(['rate', fbits(rng.choice(rates))])
elif kind == 'freeze':
ops.append(['freeze', rng.random() < 0.5])
elif kind == 'step':
ops.append(['step', rng.choice([1, 2, 5, 20, 0, -1])])
elif kind == 'sprint':
ops.append(['sprint', rng.choice([1, 2, 3, 10, 100, 0])])
elif kind in ('check', 'end'):
clock += rng.choice([0, 1, 1000, 50_000_000, 123_456_789, 3_000_000_000])
ops.append([kind, clock])
else:
ops.append([kind])
yield dict(t='rate', ops=ops)
def scale_cases(rng):
sizes = [(1, 1), (2, 2), (319, 239), (320, 240), (321, 241), (640, 480), (854, 480), (1280, 720), (1920, 1080),
(2560, 1440), (3840, 2160), (7680, 4320), (0, 0), (1000, 100), (100, 1000), (641, 481), (333, 777)]
for w, h in sizes:
for maxs in [0, 1, 2, 3, 4, 5, 6, 8, 100, -1, 7]:
for uni in (False, True):
sw, sh = rng.choice([(w, h), (max(w // 2, 1), max(h // 2, 1)), (w + 1, h + 3)])
yield dict(t='scale', w=w, h=h, max=maxs, uni=uni, sw=sw, sh=sh,
x=dbits(rng.uniform(0, w)), y=dbits(rng.uniform(0, h)))
def limit_cases(rng):
for iconified, focused in [(True, False), (True, True), (False, True)]:
for opt in (10, 30, 60, 120, 140, 260):
for afk in (False, True):
for ago in (0, 1000, 59000, 61000, 599000, 601000, 5_000_000):
for level in (False, True):
for screen in (False, True):
for overlay in (False, True):
yield dict(t='limit', iconified=iconified, focused=focused, opt=opt, afk=afk, ago=ago,
level=level, screen=screen, overlay=overlay)
def mouse_cases(rng):
for n in range(900):
sens = rng.choice([0.0, 0.5, 1.0, 0.25, 0.1, 0.75, 0.3333, rng.random()])
time = rng.choice([0.0, 10.0, 12345.678])
ops = []
for _ in range(rng.randrange(1, 40)):
kind = rng.choice(['move', 'move', 'move', 'frame', 'frame', 'ignore'])
if kind == 'move':
x, y = rng.uniform(0, 1920), rng.uniform(0, 1080)
big = rng.choice([1, 1, 1, 50, 5000])
ops.append(['move', dbits(x), dbits(y), dbits(rng.uniform(-30, 30) * big), dbits(rng.uniform(-30, 30) * big)])
elif kind == 'frame':
time += rng.choice([0.0, 0.001, 0.0069, 0.016, 0.0167, 0.05, 0.5, 2.0])
ops.append(['frame', dbits(time)])
else:
ops.append(['ignore'])
yield dict(t='mouse', sens=dbits(sens), smooth=rng.random() < 0.4, scoping=rng.random() < 0.3,
ix=rng.random() < 0.3, iy=rng.random() < 0.3, grabbed=rng.random() < 0.85, active=rng.random() < 0.9, ops=ops)
def scroll_cases(rng):
for n in range(700):
ops = []
for _ in range(rng.randrange(1, 40)):
x = rng.choice([0.0, 0.0, 0.0, 1.0, -1.0, 0.25, -0.25, 0.4, 2.0, 5.5, -7.0, rng.uniform(-3, 3)])
y = rng.choice([0.0, 1.0, -1.0, 1.0, -1.0, 0.1, -0.3, 0.5, -0.5, 2.0, -3.0, 120.0, rng.uniform(-3, 3)])
ops.append([dbits(x), dbits(y)])
yield dict(t='scroll', discrete=rng.random() < 0.4, sens=dbits(rng.choice([1.0, 0.01, 10.0, 0.5, 2.0, 3.1622776601683795])),
slot=rng.randrange(9), ops=ops)
def key_cases(rng):
for n in range(900):
toggle = rng.random() < 0.8
ops = []
for _ in range(rng.randrange(1, 50)):
ops.append(rng.choice([['option', rng.random() < 0.5], ['down', True], ['down', False], ['down', True], ['release'],
['restore'], ['click'], ['consume'], ['consume'], ['ingame']]))
yield dict(t='key', toggle=toggle, keyboard=rng.random() < 0.7, restore=rng.random() < 0.6, ops=ops)
def make_cases(build):
rng = random.Random(0x4c4f4f50)
path = build / 'cases.jsonl'
count = 0
with path.open('w') as out:
for generator in (timer_cases, rate_cases, scale_cases, limit_cases, mouse_cases, scroll_cases, key_cases):
for case in generator(rng):
out.write(json.dumps(case, separators=(',', ':')) + '\n')
count += 1
return path, count
def main():
scope = ('Real DeltaTracker.Timer (float partial ticks from integer milliseconds, pause residual, frozen partial tick, '
'real-time delta cap), ServerTickRateManager (set rate, freeze, step, sprint including the sprint report text), '
'Window.calculateScale/setGuiScale and MouseHandler scaled positions, FramerateLimitTracker throttle reasons and '
'limits (not the focus-lost exclusive-fullscreen branch, which reads SDL), MouseHandler.onMove/turnPlayer with '
'sensitivity, cinematic smoothing, scoping and inversion, Entity.turn clamps, onScroll with ScrollWheelHandler '
'accumulation, discrete scrolling and hotbar selection, and ToggleKeyMapping/KeyMapping down, click and '
'screen-release state. The frame clock source (Blaze3D.getTime, System.nanoTime) is injected, so sleeping in '
'FramerateLimiter and vsync present-mode selection are covered by Rust unit tests only.')
harness.differential(
'rust-game-loop-parity', 'VanillaGameLoopOracle', 'game_loop_probe', make_cases, scope,
sources=[lab.ROOT / f'crates/horizon-client/src/{name}.rs' for name in ('clock', 'mouse', 'window', 'keymapping')])
if __name__ == '__main__':
main()
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""Compare AbstractContainerMenu.clicked with vanilla's menu classes.
The Java oracle (VanillaMenuOracle) runs each case's clicks on the real menu
class with a stand-in player and level; the Rust example (menu_fixture) runs
horizon_client::menu. Cases are randomized slot contents with random click
sequences covering every ContainerInput (pickup, quick move, swap, clone,
throw, the three quick craft drags, pickup all) over the player inventory,
crafting table, chests, hopper, dispenser, shulker box and the furnaces. After
every click the slots, carried stack, data slots and drops are compared.
"""
import argparse
import json
import random
try:
from . import interaction_lab as lib, lab
except ImportError:
import interaction_lab as lib
import lab
MENUS = {'inventory': 46, 'crafting': 46, 'chest1': 45, 'chest2': 54, 'chest3': 63, 'chest4': 72, 'chest5': 81,
'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46}
DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10}
COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_ingot', 'diamond', 'apple', 'bread',
'oak_log', 'sand', 'bucket', 'water_bucket', 'lava_bucket', 'ender_pearl', 'snowball', 'egg', 'white_wool',
'iron_helmet', 'diamond_chestplate', 'leather_leggings', 'iron_boots', 'shield', 'carved_pumpkin',
'elytra', 'turtle_helmet', 'iron_sword', 'diamond_pickaxe', 'bow', 'shulker_box', 'red_shulker_box',
'raw_iron', 'potato', 'beef', 'chicken', 'sticky_piston', 'blaze_rod', 'lava_bucket', 'oak_sapling',
'white_dye', 'red_dye', 'torch', 'crafting_table', 'furnace', 'chest', 'glass_bottle', 'nether_wart', 'blaze_powder',
'redstone', 'gunpowder', 'sugar', 'potion', 'splash_potion', 'lingering_potion', 'fermented_spider_eye', 'dragon_breath']
def quote(text):
return '"' + text + '"'
def snbt(item, count, damage=0, curse=False, potion=None):
comps = []
if potion:
comps.append('"minecraft:potion_contents":{potion:"%s"}' % potion)
if damage:
comps.append('"minecraft:damage":%d' % damage)
if curse:
comps.append('"minecraft:enchantments":{"minecraft:binding_curse":1}')
body = ',components:{%s}' % ','.join(comps) if comps else ''
return '{id:%s,count:%d%s}' % (quote(item), count, body)
class Gen:
def __init__(self, rng, items):
self.rng = rng
self.items = items
self.pool = ['minecraft:' + c for c in COMMON if 'minecraft:' + c in items]
self.all = [k for k, v in items.items() if k != 'minecraft:air' and 'bundle' not in k
and not k.endswith('_spawn_egg')]
def stack(self):
rng = self.rng
item = rng.choice(self.pool if rng.random() < 0.85 else self.all)
info = self.items[item]
top = info.get('minecraft:max_stack_size', 64)
damage = 0
if info.get('minecraft:max_damage') and rng.random() < 0.3:
damage = rng.randrange(1, info['minecraft:max_damage'])
count = 1 if top == 1 else rng.choice([1, 1, 2, top, top, top - 1, rng.randrange(1, top + 1)])
potion = rng.choice(['minecraft:water', 'minecraft:awkward', 'minecraft:healing', 'minecraft:thick']) if item.endswith('potion') and rng.random() < 0.8 else None
return snbt(item, max(1, count), damage, curse=rng.random() < 0.15 and 'equippable' in json.dumps(info), potion=potion)
def slots(self, size, density):
return [self.stack() if self.rng.random() < density else '-' for _ in range(size)]
def recipe(self, slots, width):
"""Fills the crafting grid (slots 1..) with a small known recipe."""
rng = self.rng
amount = lambda: rng.choice([1, 1, 2, 5, 64])
choices = [[('oak_log',)], [('oak_planks',), ('oak_planks',)], [('oak_planks', 'oak_planks'), ('oak_planks', 'oak_planks')],
[('iron_ingot',) * 3] * 3, [('milk_bucket',) * 3, ('sugar', 'egg', 'sugar'), ('wheat',) * 3],
[('wheat',) * 3], [('white_wool',) * 2, ('white_wool',) * 2], [('coal',), ('stick',)]]
pattern = rng.choice(choices)
if len(pattern) > width or any(len(row) > width for row in pattern):
pattern = [('oak_planks',), ('oak_planks',)]
for y, row in enumerate(pattern):
for x, name in enumerate(row):
slots[1 + x + y * width] = snbt('minecraft:' + name, amount() if name != 'milk_bucket' else 1)
def ops(self, size):
rng = self.rng
out = []
for _ in range(rng.randrange(1, 9)):
kind = rng.choices(['PICKUP', 'QUICK_MOVE', 'SWAP', 'CLONE', 'THROW', 'DRAG', 'PICKUP_ALL', 'JUNK'],
[30, 20, 8, 3, 6, 14, 6, 2])[0]
slot = 0 if rng.random() < 0.2 and size in (46,) else rng.randrange(size)
if kind == 'PICKUP':
out.append([rng.choice([slot, slot, slot, -999, -1]), rng.randrange(0, 3), kind])
elif kind == 'QUICK_MOVE':
out.append([rng.choice([slot, slot, slot, -999, -1]), rng.randrange(0, 3), kind])
elif kind == 'SWAP':
out.append([slot, rng.choice([0, 1, 2, 3, 4, 5, 6, 7, 8, 40, 9, -1]), kind])
elif kind in ('CLONE', 'THROW', 'PICKUP_ALL'):
out.append([slot, rng.randrange(0, 2), kind])
elif kind == 'DRAG':
ty = rng.randrange(0, 4)
out.append([-999, 0 | ty << 2, 'QUICK_CRAFT'])
for _ in range(rng.randrange(0, 6)):
out.append([rng.randrange(size), 1 | ty << 2, 'QUICK_CRAFT'])
out.append([-999, 2 | ty << 2, 'QUICK_CRAFT'])
else:
out.append([rng.choice([slot, 999, -5]), rng.randrange(-1, 5), rng.choice(
['PICKUP', 'QUICK_MOVE', 'QUICK_CRAFT', 'SWAP', 'THROW', 'PICKUP_ALL'])])
return out
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', type=int, default=7)
parser.add_argument('--cases', type=int, default=6000)
parser.add_argument('--limit', type=int, default=3)
args = parser.parse_args()
work = lib.work_dir('menu-click-parity')
vanilla = lib.Vanilla(work)
vanilla.compile('ParityData', 'VanillaMenuOracle')
items = json.loads((lib.RESOURCES / 'items.json').read_text())
rng = random.Random(args.seed)
g = Gen(rng, items)
cases = []
for n in range(args.cases):
menu = list(MENUS)[n % len(MENUS)]
size = MENUS[menu]
slots = g.slots(size, rng.choice([0.1, 0.4, 0.8]))
if menu in ('inventory', 'crafting'):
slots[0] = '-'
if menu in ('inventory', 'crafting') and rng.random() < 0.6:
g.recipe(slots, 2 if menu == 'inventory' else 3)
cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots,
'carried': g.stack() if rng.random() < 0.5 else '-', 'data': [rng.choice([0, 0, 1]) if menu == 'crafter' else 0 for _ in range(DATA.get(menu, 0))],
'ops': g.ops(size)})
(work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases))
vanilla.run('VanillaMenuOracle', work / 'cases.jsonl', work / 'native.txt')
lib.cargo_example('horizon-client', 'menu_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt')
native = (work / 'native.txt').read_text().split('\n')
rust = (work / 'rust.txt').read_text().split('\n')
def by_case(lines):
out, cur = [], []
for line in lines:
cur.append(line)
if line == 'end' or line.startswith('error-case'):
out.append(cur)
cur = []
return out
native, rust = by_case(native), by_case(rust)
bad = {}
for case, a, b in zip(cases, native, rust):
if a != b:
step = next(i for i, (x, y) in enumerate(zip(a, b)) if x != y) if len(a) == len(b) else 0
op = case['ops'][step - 1] if 0 < step <= len(case['ops']) else None
bad.setdefault((case['menu'], op[2] if op else 'init'), []).append((case, step, a, b))
total = sum(len(v) for v in bad.values())
for key, entries in sorted(bad.items(), key=lambda e: -len(e[1])):
print(f'{key}: {len(entries)} differing')
for case, step, a, b in entries[:args.limit]:
print(f' ops {case["ops"][:step]}\n start {a[0]}\n native {a[step]}\n rust {b[step]}')
print(f'{len(cases) - total}/{len(cases)} cases match')
raise SystemExit(1 if total else 0)
if __name__ == '__main__':
main()
+185
View File
@@ -0,0 +1,185 @@
#!/usr/bin/env python3
"""Compare options.txt loading and saving, and the key mapping table, with the
pinned client: every file is loaded through the real Options.load and written
back with Options.save, and the Rust port must produce identical text."""
from pathlib import Path
import random
import shutil
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
VERSION = 5023
# Raw JSON-ish value texts: valid, boundary, wrong-typed, lenient-parser and
# syntax-error forms. Syntax errors abort the rest of a load, as in vanilla.
TOKENS = [
'true', 'false', 'TRUE', 'False', '"true"', '0', '1', '2', '3', '4', '5', '-1', '-3', '7', '10', '11', '12', '13',
'16', '27', '29', '30', '31', '32', '33', '60', '65', '69', '70', '71', '100', '109', '110', '111', '120', '128',
'129', '130', '255', '256', '260', '261', '1000', '2147483646', '2147483647', '2147483648', '-2147483648',
'0.0', '0.1', '0.25', '0.3', '0.5', '0.75', '0.77', '0.99', '1.0', '1.5', '2.0', '2.5', '5.0', '5.5', '6.0',
'10.0', '10.5', '-0.5', '-0.0', '1e0', '1e1', '1E-2', '1e2', '2.5e-1', '0.0001', '1e30', '12.7', '4.99',
'"fast"', '"fancy"', '"fabulous"', '"custom"', '"afk"', '"minimized"', '"left"', '"right"', '"default"',
'"opengl"', '"all"', '"none"', '"limited"', '"never"', '"pause"', '"pause_and_toast"', '"DEFAULT"', '"FREQUENT"',
'"CONSTANT"', '"false"', '"movement"', '"Fast"', "'fast'", 'fast', 'afk', 'left', 'abc', '', ' ', '""', 'null',
'[]', '[1,2]', '["vanilla"]', '["vanilla","file/x.zip"]', '{}', '[vanilla,a]', '["a<b>&=\'"]', '0.5f', '.5',
'007', '+1', 'NaN', 'Infinity', '-Infinity', '0x10', '1 2', '"unterminated', '{', ']', '1,2', '0.5 # note',
'0.5 // note', '/* c */ 0.5', '0.5;', ')]}\'\n0.5', 'tRuE', 'nul', 'true false',
]
KEY_TOKENS = [
'key.keyboard.w', 'key.keyboard.unknown', 'key.mouse.left', 'key.mouse.9', 'key.mouse.99', 'key.keyboard.200',
'key.keyboard.007', 'key.keyboard.-5', 'key.keyboard.+4', 'key.keyboard.', 'key.keyboard', 'key.mouse', 'key.mousefoo',
'key.keyboardX5', 'key.keyboard.abc', 'key.keyboard.f13', 'key.keyboard.keypad.0', 'key.keyboard.right.shift',
'', 'w', 'key.w', 'scancode.17', 'key.keyboard.4294967296', 'key.keyboard.2147483647', 'key.keyboard.2147483648',
'KEY.KEYBOARD.W', 'key.keyboard.menu', 'key.keyboard.f24',
]
PLAIN_TOKENS = ['true', 'false', 'True', '1', '0', 'yes', '', ' true', 'abc', '5', '-1', '2147483648', '+3', '007', '1.0']
STRING_TOKENS = ['en_us', 'FR_fr', '', ' a:b ', 'a:b:c', 'Ünïcode', '"quoted"', 'x' * 300]
TAIL = 'musicFrequency:"FREQUENT"\nmodelPart_hat:false\n' # shows whether a load was aborted
def option_keys():
"""Option-instance keys, read from the Rust table through the probe-independent
list below (generated from VanillaOptionsTableExporter output)."""
return ALL_KEYS
# Every key the 26.3 Options writes, in processing order (verified by the
# defaults case: a mismatch in either name or order fails the comparison).
ALL_KEYS = [
'ao', 'biomeBlendRadius', 'chunkSectionFadeInTime', 'cutoutLeaves', 'enableVsync', 'entityDistanceScaling',
'entityShadows', 'forceUnicodeFont', 'japaneseGlyphVariants', 'fov', 'fovEffectScale', 'darknessEffectScale',
'glintSpeed', 'glintStrength', 'preferredGraphicsBackend', 'graphicsPreset', 'prioritizeChunkUpdates',
'fullscreen', 'exclusiveFullscreen', 'macFullscreenMenuVisibility', 'gamma', 'guiScale', 'debugGuiScale',
'maxAnisotropyBit', 'textureFiltering', 'maxFps', 'improvedTransparency', 'inactivityFpsLimit', 'mipmapLevels',
'narrator', 'particles', 'reducedDebugInfo', 'renderClouds', 'cloudRange', 'renderDistance',
'simulationDistance', 'screenEffectScale', 'soundDevice', 'vignette', 'weatherRadius', 'autoJump',
'rotateWithMinecart', 'operatorItemsTab', 'autoSuggestions', 'chatColors', 'chatLinks', 'chatLinksPrompt',
'discrete_mouse_scroll', 'invertXMouse', 'invertYMouse', 'realmsNotifications', 'showSubtitles',
'directionalAudio', 'bobView', 'toggleCrouch', 'toggleSprint', 'toggleAttack', 'toggleUse', 'sprintWindow',
'darkMojangStudiosBackground', 'hideLightningFlashes', 'hideSplashTexts', 'mouseSensitivity',
'damageTiltStrength', 'highContrast', 'highContrastBlockOutline', 'narratorHotkey', 'resourcePacks',
'incompatibleResourcePacks', 'lastServer', 'lang', 'chatVisibility', 'chatOpacity', 'chatLineSpacing',
'textBackgroundOpacity', 'backgroundForChatOnly', 'hideServerAddress', 'advancedItemTooltips',
'pauseOnLostFocus', 'overrideWidth', 'overrideHeight', 'chatHeightFocused', 'chatDelay', 'chatHeightUnfocused',
'chatScale', 'chatWidth', 'notificationDisplayTime', 'useNativeTransport', 'mainHand', 'attackIndicator',
'tutorialStep', 'mouseWheelSensitivity', 'allowCursorChanges', 'quitShortcuts', 'ctrlClickEmulatesRightClick',
'glDebugVerbosity', 'skipMultiplayerWarning', 'hideMatchedNames', 'joinedFirstServer', 'syncChunkWrites',
'showAutosaveIndicator', 'allowServerListing', 'inGameNotification', 'sharePresence', 'onlyShowSecureChat',
'saveChatDrafts', 'panoramaScrollSpeed', 'telemetryOptInExtra', 'onboardAccessibility',
'menuBackgroundBlurriness', 'startedCleanly', 'musicToast', 'musicFrequency',
]
PLAIN = {'lastServer', 'lang', 'hideServerAddress', 'advancedItemTooltips', 'pauseOnLostFocus', 'overrideWidth',
'overrideHeight', 'useNativeTransport', 'glDebugVerbosity', 'skipMultiplayerWarning', 'joinedFirstServer',
'syncChunkWrites', 'onboardAccessibility', 'startedCleanly'}
PLAIN_STRINGS = {'lastServer', 'lang'}
MAPPINGS = None
SOUNDS = ['master', 'music', 'record', 'weather', 'block', 'hostile', 'neutral', 'player', 'ambient', 'voice', 'ui']
PARTS = ['cape', 'jacket', 'left_sleeve', 'right_sleeve', 'left_pants_leg', 'right_pants_leg', 'hat']
def write(directory, index, text, newline='\n'):
(directory / f'{index:05d}.txt').write_bytes(text.replace('\n', newline).encode('utf-8'))
def make_cases(build):
directory = build / 'cases'
shutil.rmtree(directory, ignore_errors=True)
directory.mkdir()
rng = random.Random(0x4f5054)
n = 0
# The no-file case is named absent.txt so the oracle skips the copy.
(directory / 'absent.txt').write_text('')
n += 1
header = f'version:{VERSION}\n'
# One option per file with each token: isolates every codec path.
for key in ALL_KEYS:
tokens = PLAIN_TOKENS if key in PLAIN and key not in PLAIN_STRINGS else (
STRING_TOKENS if key in PLAIN_STRINGS else TOKENS)
for token in tokens:
write(directory, n, f'{header}{key}:{token}\n{TAIL}')
n += 1
# Round trips of values the game itself would save.
for key in ALL_KEYS:
write(directory, n, f'{header}{key}:{rng.choice(TOKENS)}\n{key}:{rng.choice(TOKENS)}\n')
n += 1
# Key mappings, sound volumes and model parts.
keys = ['key.attack', 'key.use', 'key.forward', 'key.sneak', 'key.sprint', 'key.hotbar.1', 'key.swapOffhand',
'key.debug.modifier', 'key.debug.profilingChart', 'key.spectatorHotbar', 'key.nonexistent']
for key in keys:
for token in KEY_TOKENS:
write(directory, n, f'{header}key_{key}:{token}\n{TAIL}')
n += 1
for source in SOUNDS + ['nonexistent']:
for token in TOKENS[:60]:
write(directory, n, f'{header}soundCategory_{source}:{token}\n{TAIL}')
n += 1
for part in PARTS + ['nonexistent']:
for token in PLAIN_TOKENS:
write(directory, n, f'{header}modelPart_{part}:{token}\n')
n += 1
# Random multi-option files, some with CRLF/CR line ends, noise and duplicates.
syntax_errors = {'1 2', '"unterminated', '{', ']', '1,2', 'true false', '0.5 // note'}
safe = [t for t in TOKENS if t not in syntax_errors]
for _ in range(1500):
lines = [] if rng.random() < 0.1 else [f'version:{VERSION}']
for _ in range(rng.randrange(1, 40)):
key = rng.choice(ALL_KEYS)
pool = safe if rng.random() < 0.9 else TOKENS
lines.append(f'{key}:{rng.choice(PLAIN_TOKENS if key in PLAIN and key not in PLAIN_STRINGS else pool)}')
if rng.random() < 0.05:
lines.append(rng.choice(['', 'garbage', ':', 'novalue:', ':novalue', 'a:b:c', 'fullscreenResolution:1920x1080@60:24']))
newline = rng.choice(['\n', '\n', '\r\n', '\r'])
write(directory, n, '\n'.join(lines) + rng.choice(['', '\n']), newline)
n += 1
# Older files exercise the data fixers; each version boundary of the OPTIONS fixers.
legacy = [
'fancyGraphics:true\nao:2\nlang:EN_US\nchatOpacity:0.4\nmenuBackgroundBlurriness:0.5\nkey_key.forward:17\n'
'key_key.attack:-100\nkey_key.use:-99\nkey_key.pickItem:-98\nkey_key.jump:-95\nresourcePacks:["programer_art"]\n'
'showNowPlayingToast:true\n',
'fancyGraphics:false\nao:0\nkey_key.forward:key.w\nkey_key.swapHands:key.f\nmouseSensitivity:0.5\n',
'graphicsMode:2\nao:1\nmenuBackgroundBlurriness:abc\nchatOpacity:abc\nshowNowPlayingToast:false\n',
'graphicsMode:0\nmenuBackgroundBlurriness:0.35\nchatOpacity:1e-3\n',
'graphicsMode:1\nlang:Fr_Ca\nresourcePacks:["a","programer_art"]\nincompatibleResourcePacks:["programer_art"]\n',
'key_key.forward:abc\n', 'key_key.forward:\n', 'key_key.attack:k\n', 'chatOpacity:Infinity\n',
'chatOpacity: 0.5d\n', 'menuBackgroundBlurriness:0.25\n', 'menuBackgroundBlurriness:1.04999\n',
]
versions = [-1, 0, 100, 504, 505, 815, 816, 1343, 1344, 1445, 1446, 1935, 1936, 2555, 2556, 2557, 2558, 3200, 3201,
3213, 3214, 3318, 3319, 3942, 3943, 4650, 4651, 4660, 4661, 4891, 4892, 5022, 5023, 5024, 9999]
for version in versions:
for body in legacy:
write(directory, n, f'version:{version}\n{body}')
n += 1
for body in legacy:
write(directory, n, body)
n += 1
write(directory, n, f'version:abc\n{body}')
n += 1
write(directory, n, f'version: 5023\n{body}')
n += 1
for text in ['fullscreenResolution:1920x1080@60:24\n', 'fullscreenResolution:\n', 'fov:abc\nfullscreenResolution:x\n',
'fov:1 2\nfullscreenResolution:x\n', 'version:5023\nfov:0.5\n', 'FOV:0.5\n', ' fov:0.5\n', 'fov :0.5\n']:
write(directory, n, f'version:{VERSION}\n{text}')
n += 1
return directory, n
def main():
scope = ('Real Options.load and Options.save (26.3) on generated options.txt files: the full option table in '
'processing order with defaults, every codec/validator path (int ranges, quantised doubles, unit doubles with '
'boolean alternative, string and id enums with wrapping, clouds, fov, frame limit, scroll sensitivity), plain '
'fields, lenient Gson parsing and syntax-error aborts, key mappings (names, scancode-number forms, unbinding), '
'sound volumes, model parts, line endings, the OPTIONS data fixers across version boundaries, and the '
'KeyMapping table (order, defaults, categories, toggle mappings). Does not cover option screens or '
'runtime side effects of setting an option.')
harness.differential(
'rust-options-parity', 'VanillaOptionsOracle', 'options_probe', make_cases, scope,
sources=[lab.ROOT / 'crates/horizon-client/src/options_file.rs', lab.ROOT / 'crates/horizon-client/src/options_fixes.rs',
lab.ROOT / 'crates/horizon-client/src/java_text.rs', lab.ROOT / 'crates/horizon-client/src/key_names.rs',
lab.ROOT / 'crates/horizon-client/src/keybinds.rs'])
if __name__ == '__main__':
main()
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/env python3
"""Compare Horizon's resident PalettedContainer with the client's own.
Scripted edits run through vanilla's PalettedContainer (block-state and biome
strategies: single-value, linear, hash-map and global palettes, resizing, network
write and read, pack and unpack) and through horizon_core::paletted. Both sides
print the set results, the serialized container after every few edits, the
container read back from the wire, the saved form (palette, bit width, storage)
and the container loaded from it, as hashes.
"""
import argparse
import json
import os
from pathlib import Path
import platform
import random
import subprocess
try:
from . import lab, test_rust_parity as base
except ImportError:
import lab
import test_rust_parity as base
BUILD = lab.ROOT / 'target/paletted-container-parity'
LIMITS = {'blocks': (4096, 35723), 'biomes': (64, 67)}
def corpus():
rng = random.Random(0x50414C45545445)
counts = [1, 2, 3, 4, 5, 8, 9, 15, 16, 17, 31, 32, 33, 64, 100, 128, 129, 200, 256, 257, 300, 700, 2000]
for kind, (entries, ids) in LIMITS.items():
for count in counts:
if kind == 'biomes' and count > 70:
continue
for trial in range(6):
pool = rng.sample(range(ids), min(count, ids))
initial = rng.choice(pool) if trial % 2 else rng.randrange(ids)
ops = []
for _ in range(rng.choice([entries // 4, entries, entries * 3])):
ops.append((rng.randrange(entries), rng.choice(pool)))
if trial == 5:
# Every position written once, in order, then half of them reset.
ops = [(i, pool[i % len(pool)]) for i in range(entries)] + [(i, initial) for i in range(0, entries, 2)]
yield f'{kind}_{count}_{trial}', kind, initial, rng.choice([1, 7, 37, 211]), ops
# A few edits at a time: the palette grows one value at a time from a single value.
for trial in range(20):
ops = [(rng.randrange(entries), rng.randrange(ids)) for _ in range(rng.randrange(1, 40))]
yield f'{kind}_sparse_{trial}', kind, rng.randrange(ids), 1, ops
# Overwriting with the value already there, and filling a section with one value.
yield f'{kind}_fill', kind, 3, 500, [(i, 9) for i in range(entries)] + [(i, 3) for i in range(entries)]
yield f'{kind}_same', kind, 3, 1, [(i, 3) for i in range(0, entries, 5)]
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.parse_args()
lock, jars, libraries = base.verify_artifacts()
BUILD.mkdir(parents=True, exist_ok=True)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPalettedContainerOracle.java'
sources = [Path(__file__), oracle, lab.ROOT / 'tools/lab.py', lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock',
lab.ROOT / 'crates/horizon-core/Cargo.toml', lab.ROOT / 'crates/horizon-core/examples/paletted_fixture.rs',
*sorted((lab.ROOT / 'crates/horizon-core/src').rglob('*.rs'))]
tested = base.source_hashes(sources)
scenarios = list(corpus())
inputs = BUILD / 'inputs.txt'
inputs.write_text(''.join(f'{name} {kind} {initial} {every} ' + ' '.join(f'{i} {v}' for i, v in ops) + '\n'
for name, kind, initial, every, ops in scenarios))
def run(command, name):
with (BUILD / (name + '.log')).open('w') as log:
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
classes = BUILD / 'classes'
classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes, oracle], 'compile-java')
run(['cargo', 'build', '--locked', '--profile', 'fast', '-j', os.environ.get('CARGO_BUILD_JOBS', '3'), '-p', 'horizon-core', '--example', 'paletted_fixture'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT))
binary = Path(metadata['target_directory']) / 'fast/examples/paletted_fixture'
run([binary, inputs, BUILD / 'rust.txt'], 'rust')
run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPalettedContainerOracle', inputs, BUILD / 'client.txt'], 'client')
client = (BUILD / 'client.txt').read_text().splitlines()
rust = (BUILD / 'rust.txt').read_text().splitlines()
assert len(client) == len(rust) == len(scenarios), (len(client), len(rust), len(scenarios))
bad = [(a, b) for a, b in zip(client, rust) if a != b]
base.ensure_sources_unchanged(sources, tested)
for a, b in bad[:5]:
print('client', a[:600])
print('rust ', b[:600])
if bad:
raise SystemExit(f'{len(bad)} of {len(scenarios)} scenarios differ')
edits = sum(len(s[4]) for s in scenarios)
report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'scenarios': len(scenarios), 'edits': edits,
'sources_sha256': tested}
lab.write_json(BUILD / 'report.json', report)
print(f'PalettedContainer parity: {len(scenarios)} scenarios, {edits:,} edits, all hashes identical')
if __name__ == '__main__':
main()
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""Compare vanilla random ticks (and scheduled ticks) with horizon-world, state by state.
Every block state is put at the origin of a random neighbourhood and `randomTick`
(or `tick`) is run with a seeded RNG on both sides; the resulting block changes,
scheduled ticks, side effects and the RNG fingerprint after the call must match.
"""
import random
try:
from . import block_update_harness as h
except ImportError:
import block_update_harness as h
def cases(facts, count, seed, only):
rng = random.Random(seed)
pool = h.state_pool(facts, only)
for n in range(count):
state = pool[n % len(pool)]
case = {**h.environment(rng), 'pos': [0, 0, 0], 'cells': facts.cells(rng, state),
'mode': 'random' if n % 4 else 'tick'}
yield case
def main():
args = h.argument_parser(__doc__).parse_args()
facts = h.load_facts()
differing = h.execute('random-tick-parity', list(cases(facts, args.count, args.seed, args.only)), args, facts)
h.finish(differing)
if __name__ == '__main__':
main()
+303
View File
@@ -0,0 +1,303 @@
#!/usr/bin/env python3
"""Compare crafting, cooking, stonecutting and smithing with vanilla's RecipeManager.
The Java oracle (VanillaRecipeOracle) loads the data pack's recipe registry and
answers craft/cook/stonecut/smith commands; the Rust example (recipe_fixture)
answers the same commands from horizon_client::crafting and ::stations.
Crafting cases are built from every recipe's own ingredients (placed at random
offsets, mirrored, perturbed) plus focused generators for the special recipes
(banners, books, fireworks, dyeing, repair, pots, tipped arrows, maps) and
random grids. Results are compared as canonical ItemStack NBT, with the
matched recipe id and the crafting remainders.
"""
import argparse
import json
import random
try:
from . import interaction_lab as lib, lab
except ImportError:
import interaction_lab as lib
import lab
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple',
'blue', 'brown', 'green', 'red', 'black']
POTIONS = ['minecraft:healing', 'minecraft:swiftness', 'minecraft:water', 'minecraft:night_vision']
SHAPES = ['small_ball', 'large_ball', 'star', 'creeper', 'burst']
def quote(text):
return '"' + text.replace('\\', '\\\\').replace('"', '\\"') + '"'
def stack(item, count=1, **components):
"""SNBT of an ItemStack.CODEC compound; component values are SNBT text."""
body = ','.join(f'{quote("minecraft:" + key)}:{value}' for key, value in sorted(components.items()))
comp = f',components:{{{body}}}' if body else ''
return f'{{id:{quote(item)},count:{count}{comp}}}'
def colors(rng, n=None):
n = rng.randrange(0, 4) if n is None else n
return '[I;' + ','.join(str(rng.randrange(1 << 24)) for _ in range(n)) + ']'
def explosion(rng):
return ('{shape:%s,colors:%s,fade_colors:%s,has_trail:%db,has_twinkle:%db}'
% (quote(rng.choice(SHAPES)), colors(rng), colors(rng), rng.randrange(2), rng.randrange(2)))
class Gen:
def __init__(self, rng, items, recipes, patterns):
self.rng = rng
self.items = items
self.recipes = recipes
self.patterns = patterns
self.durable = [k for k, v in items.items() if v.get('minecraft:max_damage')]
def layers(self, n=None):
n = self.rng.choice([0, 0, 1, 2, 6, 7]) if n is None else n
return '[' + ','.join('{pattern:%s,color:%s}' % (quote(self.rng.choice(self.patterns)), quote(self.rng.choice(DYES))) for _ in range(n)) + ']'
def book(self, generation=None):
g = self.rng.randrange(4) if generation is None else generation
return stack('minecraft:written_book', written_book_content='{title:{raw:"T"},author:"A",generation:%d,pages:[{raw:"p1"},{raw:"p2"}]}' % g)
def stack(self, item, count=None, rich=0.5):
"""A stack of the item, with the components that apply to it."""
rng = self.rng
info = self.items.get(item, {})
count = rng.choice([1, 1, 1, 2, 3]) if count is None else count
c = {}
if rng.random() < rich:
if info.get('minecraft:max_damage') and rng.random() < 0.7:
c['damage'] = str(rng.randrange(0, info['minecraft:max_damage'] + 1))
if info.get('minecraft:max_damage') and rng.random() < 0.3:
c['enchantments'] = '{%s:1}' % quote(rng.choice(['minecraft:binding_curse', 'minecraft:vanishing_curse', 'minecraft:mending', 'minecraft:unbreaking']))
if item.endswith('_banner'):
c['banner_patterns'] = self.layers()
if item == 'minecraft:shield':
if rng.random() < 0.3:
c['banner_patterns'] = self.layers(rng.randrange(1, 3))
c['base_color'] = quote(rng.choice(DYES))
if item == 'minecraft:written_book':
return self.book()
if item == 'minecraft:firework_star':
c['firework_explosion'] = explosion(rng)
if item == 'minecraft:firework_rocket':
c['fireworks'] = '{flight_duration:%db,explosions:[%s]}' % (rng.randrange(1, 4), explosion(rng))
if item in ('minecraft:lingering_potion', 'minecraft:potion', 'minecraft:splash_potion'):
c['potion_contents'] = '{potion:%s}' % quote(rng.choice(POTIONS))
if item.startswith('minecraft:leather_') or item in ('minecraft:wolf_armor',):
if rng.random() < 0.6:
c['dyed_color'] = str(rng.randrange(1 << 24))
if item.endswith('shulker_box'):
c['container'] = '[{slot:0,item:{id:"minecraft:stone",count:%d}}]' % rng.randrange(1, 64)
if item.endswith('_bundle') or item == 'minecraft:bundle':
c['bundle_contents'] = '[{id:"minecraft:stone",count:%d}]' % rng.randrange(1, 64)
if item == 'minecraft:filled_map':
c['map_id'] = str(rng.randrange(1, 5))
return stack(item, count, **c)
def plain(self, item):
return self.stack(item, rich=0.3)
def place(rng, cells, size):
"""Cells (stack list) at random free positions of a size x size grid."""
grid = ['-'] * (size * size)
spots = rng.sample(range(size * size), len(cells))
for spot, cell in zip(spots, cells):
grid[spot] = cell
return grid
def place_box(rng, width, height, cells, size):
"""A width x height pattern at a random offset of the grid."""
x0 = rng.randrange(size - width + 1)
y0 = rng.randrange(size - height + 1)
grid = ['-'] * (size * size)
for i, cell in enumerate(cells):
grid[(y0 + i // width) * size + x0 + i % width] = cell
return grid
def craft_case(grid, size):
return 'craft\t%d\t%s' % (size, '\t'.join(grid))
def recipe_cases(g, count_per):
rng = g.rng
for recipe in g.recipes:
if 'slots' not in recipe or not recipe['ingredients']:
continue
ingredients = recipe['ingredients']
slots = recipe['slots']
shaped = recipe['kind'] == 'ShapedRecipe'
if shaped:
width = recipe['width']
height = len(slots) // width
for variant in range(count_per):
pick = [g.plain(rng.choice(i)) if i else '-' for i in ingredients]
if shaped:
cells = ['-' if s < 0 else pick[s] for s in slots]
if variant % 3 == 1: # mirrored
cells = [cells[y * width + width - 1 - x] for y in range(height) for x in range(width)]
size = rng.choice([s for s in (2, 3) if s >= max(width, height)])
grid = place_box(rng, width, height, cells, size)
else:
size = 3 if len(pick) > 4 else rng.choice([2, 3])
grid = place(rng, pick, size)
yield craft_case(grid, size)
# Perturbations: drop one, swap one for a stranger, add one, shift a count.
if variant < 2:
filled = [i for i, c in enumerate(grid) if c != '-']
broken = list(grid)
broken[rng.choice(filled)] = '-'
yield craft_case(broken, size)
broken = list(grid)
broken[rng.choice(filled)] = g.plain(rng.choice([i for i in g.items if i != 'minecraft:air']))
yield craft_case(broken, size)
free = [i for i, c in enumerate(grid) if c == '-']
if free:
broken = list(grid)
broken[rng.choice(free)] = g.plain(rng.choice([i for i in g.items if i != 'minecraft:air']))
yield craft_case(broken, size)
def special_cases(g, n):
rng = g.rng
items = g.items
banners = [f'minecraft:{d}_banner' for d in DYES]
dyes = [f'minecraft:{d}_dye' for d in DYES]
armor = [k for k in items if k.startswith('minecraft:leather_') and k.count('_') == 2] + ['minecraft:wolf_armor']
boxes = [k for k in items if k.endswith('shulker_box')]
bundles = [k for k in items if k.endswith('bundle')]
skulls = [k for k in items if k.endswith('_head') or k.endswith('_skull')]
for _ in range(n):
size = rng.choice([2, 3])
# banner duplicate / shield decoration
a, b = rng.choice(banners), rng.choice(banners)
yield craft_case(place(rng, [g.stack(a, 1, 1.0), g.stack(b if rng.random() < 0.3 else a, 1, 0.5)], size), size)
yield craft_case(place(rng, [g.stack(rng.choice(banners), 1, 1.0), g.stack('minecraft:shield', 1, 0.5)], size), size)
# book cloning
books = [g.book(rng.choice([0, 0, 1, 2, 3]))] + [stack('minecraft:writable_book') for _ in range(rng.randrange(0, 4))]
if rng.random() < 0.2:
books.append(g.book())
yield craft_case(place(rng, books, 3), 3)
# fireworks
star = [stack(rng.choice(['minecraft:gunpowder'] + dyes[:2] + ['minecraft:gold_nugget', 'minecraft:feather', 'minecraft:fire_charge',
'minecraft:diamond', 'minecraft:glowstone_dust', rng.choice(skulls)]))
for _ in range(rng.randrange(1, 7))]
star += [stack('minecraft:gunpowder'), stack(rng.choice(dyes))]
yield craft_case(place(rng, star[:9], 3), 3)
fade = [g.stack('minecraft:firework_star', 1, 1.0)] + [stack(rng.choice(dyes)) for _ in range(rng.randrange(1, 4))]
yield craft_case(place(rng, fade, 3), 3)
rocket = [stack('minecraft:paper')] + [stack('minecraft:gunpowder') for _ in range(rng.randrange(0, 5))] + \
[g.stack('minecraft:firework_star', 1, 1.0) for _ in range(rng.randrange(0, 4))]
yield craft_case(place(rng, rocket[:9], 3), 3)
# armour dyeing, with leftovers
dye_cells = [g.stack(rng.choice(armor), 1, 0.7)] + [stack(rng.choice(dyes + ['minecraft:stick'] if rng.random() < 0.1 else dyes)) for _ in range(rng.randrange(1, 5))]
yield craft_case(place(rng, dye_cells[:9], 3), 3)
# repair
tool = rng.choice(g.durable)
pair = [g.stack(tool, 1, 1.0), g.stack(tool if rng.random() < 0.85 else rng.choice(g.durable), 1, 1.0)]
yield craft_case(place(rng, pair, size), size)
# shulker boxes and bundles
yield craft_case(place(rng, [g.stack(rng.choice(boxes + bundles), 1, 1.0), stack(rng.choice(dyes))], size), size)
multi = [g.stack(rng.choice(boxes + bundles), 1, 1.0)] + [stack(rng.choice(dyes)) for _ in range(rng.randrange(1, 4))]
yield craft_case(place(rng, multi, 3), 3)
# decorated pots
sherds = ['minecraft:brick', 'minecraft:angler_pottery_sherd', 'minecraft:archer_pottery_sherd', 'minecraft:stick', 'minecraft:blade_pottery_sherd']
pot = ['-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-', stack(rng.choice(sherds)), '-']
if rng.random() < 0.2:
pot[rng.choice([0, 2, 6, 8, 4])] = stack('minecraft:brick')
yield craft_case(pot, 3)
yield craft_case([stack('minecraft:brick') if i in (1, 3, 5, 7) else '-' for i in range(9)], 3)
# tipped arrows
ring = [stack('minecraft:arrow', rng.choice([1, 2]))] * 9
ring[4] = g.stack('minecraft:lingering_potion', 1, 1.0 if rng.random() < 0.8 else 0.0)
yield craft_case(ring, 3)
# map cloning
maps = [g.stack('minecraft:filled_map', 1, 1.0)] + [stack('minecraft:map') for _ in range(rng.randrange(1, 9))]
yield craft_case(place(rng, maps, 3), 3)
# mixed junk of the interesting items
pool = banners + dyes + armor + boxes + bundles + ['minecraft:written_book', 'minecraft:writable_book', 'minecraft:firework_star',
'minecraft:paper', 'minecraft:gunpowder', 'minecraft:shield', 'minecraft:glass_bottle',
'minecraft:milk_bucket', 'minecraft:honey_bottle', 'minecraft:bowl', 'minecraft:stick']
junk = [g.stack(rng.choice(pool), None, 0.7) for _ in range(rng.randrange(1, 6))]
yield craft_case(place(rng, junk, 3), 3)
def smithing_cases(g):
rng = g.rng
for recipe in g.recipes:
if recipe['kind'].startswith('Smithing'):
for _ in range(24):
pick = lambda key: g.plain(rng.choice(recipe[key])) if recipe[key] else '-'
yield 'smith\t%s\t%s\t%s' % (pick('template'), pick('base'), pick('addition'))
yield 'smith\t%s\t%s\t%s' % (pick('template'), pick('base'), g.plain(rng.choice([i for i in g.items if i != 'minecraft:air'])))
# Armour with a trim already on it.
trims = ['{material:"minecraft:iron",pattern:"minecraft:coast"}', '{material:"minecraft:gold",pattern:"minecraft:sentry"}']
for recipe in g.recipes:
if recipe['kind'] == 'SmithingTrimRecipe':
for trim in trims:
base = rng.choice(recipe['base'])
yield 'smith\t%s\t%s\t%s' % (stack(rng.choice(recipe['template'])), stack(base, 1, trim=trim), stack(rng.choice(recipe['addition'])))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', type=int, default=7)
parser.add_argument('--variants', type=int, default=6)
parser.add_argument('--specials', type=int, default=1500)
parser.add_argument('--random', type=int, default=4000)
parser.add_argument('--limit', type=int, default=3)
args = parser.parse_args()
work = lib.work_dir('recipe-parity')
vanilla = lib.Vanilla(work)
vanilla.compile('ParityData', 'VanillaRecipeOracle')
vanilla.run('VanillaRecipeOracle', 'dump', work / 'recipes.jsonl')
recipes = [json.loads(line) for line in (work / 'recipes.jsonl').read_text().splitlines()]
# Shaped recipes: widths come from the data pack.
for recipe in recipes:
path = lib.RESOURCES / 'data/minecraft/recipe' / (recipe['id'] + '.json')
data = json.loads(path.read_text())
if recipe['kind'] == 'ShapedRecipe':
rows = [row.rstrip() for row in data['pattern']]
left = min(len(row) - len(row.lstrip()) for row in rows if row)
recipe['width'] = max(len(row) for row in rows) - left
items = json.loads((lib.RESOURCES / 'items.json').read_text())
patterns = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/banner_pattern').glob('*.json'))
rng = random.Random(args.seed)
g = Gen(rng, items, recipes, patterns)
cases = list(recipe_cases(g, args.variants))
cases += list(special_cases(g, args.specials))
pool = [k for k in items if not k.endswith('_spawn_egg') and k != 'minecraft:air']
interesting = [f'minecraft:{d}_dye' for d in DYES] + ['minecraft:paper', 'minecraft:gunpowder', 'minecraft:bowl', 'minecraft:stick',
'minecraft:milk_bucket', 'minecraft:honey_bottle', 'minecraft:water_bucket']
for _ in range(args.random):
size = rng.choice([2, 3])
cells = [g.stack(rng.choice(interesting if rng.random() < 0.6 else pool), None, 0.5) for _ in range(rng.randrange(1, size * size + 1))]
cases.append(craft_case(place(rng, cells, size), size))
for kind in ['smelting', 'blasting', 'smoking', 'campfire_cooking']:
for item in [i for i in items if i != 'minecraft:air']:
cases.append('cook\t%s\t%s' % (kind, stack(item)))
for item in [i for i in items if i != 'minecraft:air']:
cases.append('stonecut\t' + stack(item))
cases += list(smithing_cases(g))
(work / 'cases.txt').write_text(''.join(c + '\n' for c in cases))
vanilla.run('VanillaRecipeOracle', work / 'cases.txt', work / 'native.txt')
lib.cargo_example('horizon-client', 'recipe_fixture', lib.RESOURCES, work / 'cases.txt', work / 'rust.txt')
def key(case, native_line):
kind = case.split('\t')[0]
return kind if kind != 'craft' else 'craft ' + native_line.split('\t')[0]
def describe(case):
return case if len(case) < 1200 else case[:1200] + '...'
total = lib.compare(cases, work / 'native.txt', work / 'rust.txt', key, describe, args.limit)
raise SystemExit(1 if total else 0)
if __name__ == '__main__':
main()
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""Compare vanilla redstone circuits with horizon-world, tick by tick.
A small floor carries randomly placed redstone components (wire, repeaters,
comparators, torches, observers, pistons, lamps, rails, plates, buttons...). A power
source is placed and later removed through `Level.setBlock` and the scheduled-tick
queue is run for N game ticks; the block changes and pending ticks after every
tick (and the RNG fingerprint at the end) must match.
"""
import random
try:
from . import block_update_harness as h
except ImportError:
import block_update_harness as h
COMPONENTS = [
'redstone_wire', 'redstone_wire', 'redstone_wire', 'redstone_wire', 'repeater', 'repeater', 'comparator', 'redstone_torch',
'redstone_wall_torch', 'observer', 'piston', 'sticky_piston', 'redstone_lamp', 'lever', 'stone_button', 'oak_button',
'stone_pressure_plate', 'note_block', 'target', 'dropper', 'dispenser', 'hopper', 'rail', 'powered_rail', 'activator_rail',
'detector_rail', 'oak_door', 'iron_door', 'oak_trapdoor', 'oak_fence_gate', 'tnt', 'slime_block', 'honey_block', 'stone',
'redstone_block', 'daylight_detector', 'trapped_chest', 'copper_bulb', 'sculk_sensor', 'tripwire_hook', 'lectern',
'oak_slab', 'iron_block', 'glass', 'crafter',
]
def build(facts, rng):
floor = facts.defaults['minecraft:stone']
names = [n for n in ('minecraft:' + c for c in COMPONENTS) if n in facts.by_block]
cells = []
for x in range(-4, 5):
for z in range(-4, 5):
cells.append([x, -1, z, floor])
if rng.random() < 0.5:
name = rng.choice(names)
states = facts.by_block[name]
state = rng.choice(states)
cells.append([x, 0, z, state])
if rng.random() < 0.15:
cells.append([x, 1, z, rng.choice(facts.by_block[rng.choice(names)])])
return cells
def cases(facts, count, seed, only):
rng = random.Random(seed)
source = facts.defaults['minecraft:redstone_block']
air = facts.defaults['minecraft:air']
for n in range(count):
cells = build(facts, rng)
at = [rng.randrange(-4, 5), 0, rng.randrange(-4, 5)]
cells = [c for c in cells if c[:3] != at]
cells.append([*at, air])
case = {**h.environment(rng), 'mode': 'run', 'pos': [0, -1, 0], 'cells': cells, 'ops': [
{'op': 'set', 'pos': at, 'state': source, 'flags': 3},
{'op': 'ticks', 'n': 12, 'snap': True},
{'op': 'set', 'pos': at, 'state': air, 'flags': 3},
{'op': 'ticks', 'n': 12, 'snap': True},
]}
case.pop('raining', None)
yield case
def main():
args = h.argument_parser(__doc__).parse_args()
args.count = min(args.count, 4000) if args.count == 40000 else args.count
facts = h.load_facts()
differing = h.execute('redstone-parity', list(cases(facts, args.count, args.seed, args.only)), args, facts)
h.finish(differing)
if __name__ == '__main__':
main()
+9 -4
View File
@@ -56,12 +56,15 @@ IGNORED = {
# chunk generation first), so counters and positions of live things move on.
r'^chunk\.block_entities\.\(2, -60, 5\)\.(cooking_time_spent|lit_time_remaining|Items\[\]\.count)$':
'the lit furnace keeps smelting',
r'^chunk\.block_entities\..*\.(ticks_since_song_started|Age|BrewTime|warning_level|ticks_in_hive)$':
r'^chunk\.block_entities\..*\.(ticks_since_song_started|Age|BrewTime|warning_level|ticks_in_hive|last_vibration_frequency|listener\..*|RecipesUsed\..*)$':
'block entity timers advance',
r'^entity\.(Age|Motion\[\]|Rotation\[\]|Pos\[\]|OnGround|HurtTime|Health|TimeInOverworld|fall_distance|'
r'wasOnGround|Fire|Air|DeathTime|Fuse|life|inGround|ticks_in_ground)$': 'entity simulation advances',
r'^level\.dat\.Data\.(Time|LastPlayed)$': 'clock and wall time of the save',
r'^level\.dat\.Data\.(ServerBrands.*|singleplayer_uuid)$': 'a client world names its brand and its player',
r'^entity\.listener\.selector\.(event|tick)$': 'the warden listener holds the last vibration it heard; timing',
r'^players/data/.*\.dat\.warden_spawn_tracker\.': 'counts ticks since the last warning; timing',
r'^players/data/.*\.dat\.recipeBook\.(recipes|toBeDisplayed)': 'which recipes unlock depends on the pickup history of the bot',
r'^players/data/.*\.dat\.(Health|Pos\[\]|foodSaturationLevel|foodLevel|foodExhaustionLevel|Motion\[\]|OnGround)$':
'the player keeps simulating',
}
@@ -69,6 +72,7 @@ IGNORED = {
# Real differences that are known and not fixed yet: (pattern -> what is wrong). They are
# reported, and do not fail the run, so that new differences still do.
KNOWN_GAPS = {
r'^chunk\.block_entities\.\(26, -60, 5\)\.triggered': 'crafter: Horizon derives the BE flag from the block state each tick instead of in neighborChanged',
r'^chunk\.sections\.blocks|^chunk\.Heightmaps': 'a falling block entity with NoGravity lands anyway',
r'^entity \(28672, 0, 0, 11\)': 'the spider is gone from the Horizon save (not yet explained)',
r'^entity \(28672, 0, 0, 30\) minecraft:falling_block': 'the NoGravity falling block landed (above)',
@@ -532,7 +536,8 @@ def main():
print('vanilla log (Horizon save):', line)
failures += 1
volatile = re.compile(r'(cooking_time_spent|lit_time_remaining|ticks_since_song_started|Age|BrewTime|'
r'ticks_in_hive|state_updating_resumes_at|LastExecution|last_vibration_frequency|warning_level): -?[0-9]+[a-zA-Z]?')
r'ticks_in_hive|triggered|state_updating_resumes_at|LastExecution|last_vibration_frequency|warning_level): -?[0-9]+[a-zA-Z]?')
volatile2 = re.compile(r'(RecipesUsed: \{[^}]*\}|listener: \{.*\}(?=, x))')
for label in views0:
if label.startswith('entity'):
# Entity data moves with the simulation: only require vanilla to load it.
@@ -542,8 +547,8 @@ def main():
print(f'VANILLA cannot find {label} in the Horizon save')
failures += 1
continue
if volatile.sub('', views0[label]) != volatile.sub('', views1.get(label, '')):
print(f'VANILLA VIEW differs: {label}\n V0 {views0[label][:300]}\n H {str(views1.get(label))[:300]}')
if volatile2.sub('', volatile.sub('', views0[label])) != volatile2.sub('', volatile.sub('', views1.get(label, ''))):
print(f'VANILLA VIEW differs: {label}\n V0 {views0[label][:900]}\n H {str(views1.get(label))[:900]}')
failures += 1
print('save round-trip parity', 'FAILED' if failures else 'ok', f'({failures} unexplained differences)')
if not args.keep and not failures:
+73 -2
View File
@@ -29,6 +29,7 @@ except ImportError:
import test_model_baking_parity as baking
BUILD = lab.ROOT / 'target/section-mesh-parity'
RESOURCES = lab.LOCAL / 'horizon-client' / '26.3'
SECTION_Y = 0
COLORS = {'grass': 0x91BD59, 'foliage': 0x77AB2F, 'dry_foliage': 0xA88B5E, 'water': 0x3F76E4}
POSITION_TOLERANCE = 1e-4
@@ -71,6 +72,8 @@ class Scene:
self.blocks = {}
self.light_override = {}
self.noise = None
self.biomes = None
self.options = {}
def put(self, x, y, z, name, **properties):
self.blocks[(x, y, z)] = name if isinstance(name, int) else self.states(name, **properties)
@@ -130,8 +133,38 @@ class Scene:
return result
def row(self):
return {'name': self.name, 'nether': self.nether, 'section_y': SECTION_Y, 'colors': COLORS, 'light': [15, 0],
'blocks': [[*p, s] for p, s in sorted(self.blocks.items())], 'lights': self.lights()}
row = {'name': self.name, 'nether': self.nether, 'section_y': SECTION_Y, 'colors': COLORS, 'light': [15, 0],
'blocks': [[*p, s] for p, s in sorted(self.blocks.items())], 'lights': self.lights()}
if self.biomes is not None:
row['biomes'] = self.biomes
row.update(self.options)
return row
def tinted_columns(self):
"""Every tint source at several heights over the section's 16x16 footprint."""
names = [('grass_block', {}), ('short_grass', {}), ('oak_leaves', {}), ('water', {}), ('leaf_litter', {'segment_amount': 2}),
('sugar_cane', {}), ('fern', {}), ('vine', {'north': True}), ('mangrove_leaves', {}), ('jungle_leaves', {})]
for x in range(16):
for z in range(16):
for layer, y in enumerate((1, 5, 9, 13)):
name, properties = names[(x * 5 + z * 3 + layer) % len(names)]
self.put(x, y, z, 'stone')
self.put(x, y + 1, z, name, **properties)
if name == 'water':
self.put(x, y + 2, z, 'water')
def biome_field(self, seed, radius, names, default='plains'):
"""Noise-biome quart cells: a Voronoi patchwork that shifts with height."""
rng = random.Random(seed)
sites = [[(rng.uniform(-4, 8), rng.uniform(-4, 8), rng.choice(names)) for _ in range(9)] for _ in range(10)]
cells = []
for qy in range(-3, 8):
layer = sites[(qy + 3) // 2 % len(sites)]
for qx in range(-4, 8):
for qz in range(-4, 8):
best = min(layer, key=lambda site: (site[0] - qx) ** 2 + (site[1] - qz) ** 2)
cells.append([qx, qy, qz, 'minecraft:' + best[2]])
self.biomes = {'seed': rng.randrange(-2 ** 63, 2 ** 63), 'radius': radius, 'default': 'minecraft:' + default, 'cells': cells}
def corpus(states, full=True):
@@ -306,6 +339,38 @@ def corpus(states, full=True):
s.put(rng.randrange(-1, 17), rng.randrange(-1, 17), rng.randrange(-1, 17), rng.choice(ids))
if seed % 2:
s.noise = seed
# Biome tint blending: BiomeManager's zoomed biome at each block's own height, averaged
# over the blend radius, for real biome colours (colormaps, overrides, modifiers).
biome_names = sorted(path.stem for path in (RESOURCES / 'data/minecraft/worldgen/biome').glob('*.json'))
common = ['plains', 'swamp', 'dark_forest', 'desert', 'jungle', 'badlands', 'mangrove_swamp', 'warm_ocean', 'snowy_plains',
'birch_forest', 'cherry_grove', 'pale_garden', 'savanna', 'taiga', 'old_growth_pine_taiga', 'lush_caves']
for i, radius in enumerate((2, 0, 1, 3, 5, 7)):
s = scene(f'biome_blend_r{radius}')
s.floor(0)
s.tinted_columns()
s.biome_field(0x42494F4D + i, radius, common)
for i in range(0, len(biome_names), 8):
s = scene(f'biome_each_{i // 8}')
s.tinted_columns()
s.biome_field(0x45414348 + i, 2, biome_names[i:i + 8], biome_names[i])
# Options: flat lighting (ao off) and opaque leaves (cutoutLeaves off) alone and together.
leaves = ['oak_leaves', 'spruce_leaves', 'birch_leaves', 'jungle_leaves', 'acacia_leaves', 'dark_oak_leaves',
'azalea_leaves', 'flowering_azalea_leaves', 'mangrove_leaves', 'cherry_leaves', 'pale_oak_leaves']
option_palette = ['stone', 'glass', 'grass_block', 'water', 'lava', 'oak_slab', 'oak_stairs', 'torch', 'poppy', 'short_grass',
'glowstone', 'oak_fence', 'ice', 'oak_log', 'tinted_glass', 'slime_block', 'honey_block'] + leaves * 2
for i, options in enumerate(({'smooth': False}, {'cutout_leaves': False}, {'smooth': False, 'cutout_leaves': False})):
rng = random.Random(0x4F505453 + i)
s = scene(f'options_{i}', nether=i == 2)
s.options = options
s.floor(0)
for x in range(-1, 17):
for y in range(1, 17):
for z in range(-1, 17):
if rng.random() < 0.5:
name = rng.choice(option_palette)
s.put(x, y, z, rng.choice(states.by_name['minecraft:' + name]))
if i:
s.noise = i
s = scene('cubes_nether', nether=True)
s.floor(3, 'netherrack')
s.fill(4, 4, 4, 6, 6, 6, 'nether_bricks')
@@ -337,6 +402,7 @@ def light(coords):
def compare(scene, client, rust, states, report, limit):
blend_zero = scene.get('biomes', {}).get('radius') == 0
blocks = {tuple(b[:3]): b[3] for b in scene['blocks']}
def describe(quad, rotation):
v = quad['vertices']
@@ -377,6 +443,11 @@ def compare(scene, client, rust, states, report, limit):
if any(abs(p[i] - q[i]) > UV_TOLERANCE for i in (3, 4)):
problems.add('uv')
cp, cq = channels(p[5]), channels(q[5])
if blend_zero and cp[3] == 0 and cq[3] == 255:
# With biomeBlendRadius 0 the client uses the resolver's colour as is,
# and biome colours given as plain RGB have alpha 0: tinted vertices come
# out fully transparent. Horizon keeps them opaque; RGB is compared.
cp[3] = 255
if cp != cq:
problems.add('color' if max(abs(x - y) for x, y in zip(cp, cq)) > 1 else 'color_rounding')
if light(p[6]) != light(q[6]):
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Upgrade a world saved by an older Minecraft version to the 26.3 DataVersion.
Horizon reads chunks only at the current DataVersion and has not ported the
DataFixerUpper chain. This runs vanilla's own upgrader (`server.jar --forceUpgrade
--eraseCache`) on a copy of the world, so every fix vanilla applies (chunk, entity, POI,
level.dat, player and data/*.dat files) is applied exactly. The original is kept.
upgrade_world.py SOURCE_WORLD DEST_WORLD
"""
import random
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
SERVER = ROOT / '.local' / 'minecraft' / '26.3' / 'jars' / 'server.jar'
def main():
if len(sys.argv) != 3:
sys.exit(__doc__)
source, dest = Path(sys.argv[1]), Path(sys.argv[2])
if not (source / 'level.dat').is_file():
sys.exit(f'{source} is not a world (no level.dat)')
if dest.exists():
sys.exit(f'{dest} exists already')
with tempfile.TemporaryDirectory(prefix='hzupgrade') as scratch:
scratch = Path(scratch)
(scratch / 'eula.txt').write_text('eula=true\n')
(scratch / 'server.properties').write_text(
f'level-name=world\nonline-mode=false\nserver-port={random.randint(30000, 60000)}\n')
shutil.copytree(source, scratch / 'world')
# The server upgrades at startup, then keeps running as a normal server: stop it
# once it reports "Done".
server = subprocess.Popen(
['java', '-jar', str(SERVER), '--nogui', '--forceUpgrade', '--eraseCache'],
cwd=scratch, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
for line in server.stdout:
sys.stdout.write(line)
if 'Done (' in line:
server.stdin.write('stop\n')
server.stdin.flush()
if server.wait():
sys.exit('vanilla upgrade failed')
shutil.move(str(scratch / 'world'), str(dest))
print(f'upgraded world written to {dest}')
if __name__ == '__main__':
main()