Merge main into agent branch

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 09:57:55 +02:00
98 changed files with 13539 additions and 1293 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()
+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()
+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()
+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]):