Merge remote-tracking branch 'origin/t3/achieve-full-parity' into parity/rendering-anim

This commit is contained in:
Ludovic Marie
2026-10-12 12:43:27 +02:00
178 changed files with 25164 additions and 3896 deletions
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""Shared runner for the audio differential harnesses.
Each harness writes an input file, runs a Java oracle against the pinned
client (the real SoundManager / SoundEngine / MusicManager / ambient handlers;
OpenAL runs on OpenAL Soft's "No Output" device so channel parameters can be
read back from real AL sources) and a Rust example replaying the same inputs
through Horizon's audio code, then requires byte-identical output.
"""
import json
import os
from pathlib import Path
import platform
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
RESOURCES = lab.LOCAL / 'horizon-client/26.3'
COMMON_SOURCES = [
lab.ROOT / 'tools/audio_harness.py',
lab.ROOT / 'tools/test_rust_parity.py',
lab.ROOT / 'tools/lab.py',
lab.ROOT / 'Cargo.toml',
lab.ROOT / 'Cargo.lock',
lab.ROOT / 'crates/horizon-client/Cargo.toml',
lab.ROOT / 'crates/horizon-client/src/sound_events.rs',
lab.ROOT / 'crates/horizon-client/src/sound_engine.rs',
]
def require_sounds():
if not (RESOURCES / 'assets/minecraft/sounds.json').is_file():
raise SystemExit('Sound assets missing: run tools/fetch_sounds.py first')
def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args=(), rust_args=(), scope='', timeout=1800):
"""Run oracle and example on inputs; returns the number of matched lines."""
require_sounds()
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
build = lab.LOCAL / f'rust-{name}'
build.mkdir(parents=True, exist_ok=True)
report = build / 'report.json'
report.unlink(missing_ok=True)
oracle_path = lab.ROOT / f'mods/horizon/src/test/java/dev/horizonlab/parity/{oracle}.java'
example_path = lab.ROOT / f'crates/horizon-client/examples/{example}.rs'
sources = [*COMMON_SOURCES, oracle_path, example_path, *[Path(s) for s in extra_sources]]
tested = base.source_hashes(sources)
inputs = build / 'inputs.txt'
inputs.write_text(inputs_text)
input_hash = lab.digest(inputs, 'sha256')
def run(command, log, env=None):
with (build / (log + ".log")).open("w") as out:
try:
subprocess.run(list(map(str, command)), cwd=lab.ROOT, check=True, timeout=timeout, stdout=out, stderr=subprocess.STDOUT, env=env)
except subprocess.CalledProcessError:
raise SystemExit(f"{log} failed: see {build / (log + '.log')}") from None
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', '-sourcepath', lab.ROOT / 'mods/horizon/src/test/java',
'-cp', dependencies, '-d', classes, oracle_path], 'compile-java')
run(['cargo', 'build', '--locked', '-p', 'horizon-client', '--example', example], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT))
binary = Path(metadata['target_directory']) / 'debug/examples' / (example + ('.exe' if os.name == 'nt' else ''))
run([binary, *rust_args, inputs, build / 'rust.txt'], 'rust')
env = dict(os.environ, ALSOFT_DRIVERS='null')
run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, f'dev.horizonlab.parity.{oracle}', *java_args, inputs, build / 'client.txt'],
'client', env=env)
matched = base.compare(build / 'client.txt', build / 'rust.txt')
base.ensure_sources_unchanged(sources, tested)
if input_hash != lab.digest(inputs, '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],
sources_sha256=tested, input_sha256=input_hash, client_jar_sha256=lab.digest(jars['client'], 'sha256'),
sounds_json_sha256=lab.digest(RESOURCES / 'assets/minecraft/sounds.json', 'sha256'),
matched_output_lines=matched, output_sha256=lab.digest(build / 'rust.txt', 'sha256'), scope=scope))
return matched, report
def bits(value):
import struct
return struct.pack('>f', value).hex()
+1 -1
View File
@@ -66,7 +66,7 @@ def main():
names = sorted({k[0] for k in vanilla} | {k[0] for k in errors})
subprocess.run(['cargo', 'build', '--profile', 'fast', '-q', '-p', 'horizon-world', '--example', 'loot_fill'],
check=True, cwd=lab.ROOT)
rust_out = subprocess.run([str(lab.ROOT/'target/fast/examples/loot_fill'), resources, ','.join(names), *seeds],
rust_out = subprocess.run([str(lab.cargo_target()/'fast/examples/loot_fill'), resources, ','.join(names), *seeds],
check=True, capture_output=True, text=True).stdout
rust, _ = parse(rust_out.splitlines())
matched = differ = 0
+1 -1
View File
@@ -77,7 +77,7 @@ def main():
vanilla = parse(out.read_text().splitlines())
subprocess.run(['cargo', 'build', '--profile', 'fast', '-q', '-p', 'horizon-world', '--example', 'structure_blocks'],
check=True, cwd=lab.ROOT)
rust_out = subprocess.run([str(lab.ROOT/'target/fast/examples/structure_blocks'), resources, seed, dimension, *targets],
rust_out = subprocess.run([str(lab.cargo_target()/'fast/examples/structure_blocks'), resources, seed, dimension, *targets],
check=True, capture_output=True, text=True).stdout
(build_dir()/'rust.txt').write_text(rust_out)
rust = parse(rust_out.splitlines())
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""The check a branch must pass before it merges into the integration branch.
python3 tools/gate.py # everything
python3 tools/gate.py --no-parity # skip the vanilla harnesses
python3 tools/gate.py --quick # formatting, lints and Python tests only
python3 tools/gate.py --known-failures mob_ai,light # harnesses already failing on the base
Runs, in order, stopping at the first failure: the public-tree check,
rustfmt, clippy with warnings denied, the Rust tests, the Python tests, and
then every vanilla harness whose inputs changed (tools/parity.py). Harnesses
listed with --known-failures may still fail (they fail on the integration
branch too); any other failing harness fails the gate. CI runs the
same Rust and Python checks; the harnesses are the part CI cannot run.
The result is written to .local/gate.json.
"""
import argparse
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
ROOT = Path(__file__).resolve().parents[1]
RESULT = ROOT / ".local" / "gate.json"
def steps(args):
yield "public tree", [sys.executable, "tools/check_public_tree.py"]
yield "rustfmt", ["cargo", "+stable", "fmt", "--all", "--", "--check"]
yield "clippy", ["cargo", "+stable", "clippy", "--locked", "--workspace", "--all-targets", "--", "-D", "warnings"]
if args.quick:
yield "python tests", [sys.executable, "-m", "unittest", "discover", "-s", "tests", "-q"]
return
# Clippy has already compiled the examples; building them again for the
# test run is most of the time and disk `cargo test --workspace` takes.
yield "rust tests", ["cargo", "+stable", "test", "--locked", "--workspace", "--lib", "--bins", "--tests"]
yield "doc tests", ["cargo", "+stable", "test", "--locked", "--workspace", "--doc"]
yield "python tests", [sys.executable, "-m", "unittest", "discover", "-s", "tests", "-q"]
if not args.no_parity:
yield "vanilla harnesses", [sys.executable, "tools/parity.py", "-j", str(args.jobs)]
def head():
return subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True).stdout.strip()
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--no-parity", action="store_true", help="skip the vanilla harnesses")
parser.add_argument("--quick", action="store_true", help="only formatting, lints and Python tests")
parser.add_argument("--known-failures", default="", help="comma-separated harnesses allowed to keep failing")
parser.add_argument("-j", "--jobs", type=int, default=max(1, (os.cpu_count() or 4) // 3), help="parallel harnesses")
args = parser.parse_args()
logs = ROOT / ".local" / "gate"
logs.mkdir(parents=True, exist_ok=True)
commit, dirty = head(), bool(subprocess.run(["git", "status", "--porcelain"], cwd=ROOT, capture_output=True, text=True).stdout.strip())
results = []
passed = True
for name, command in steps(args):
started = time.monotonic()
log = logs / (name.replace(" ", "-") + ".log")
print(f"{name}...", end=" ", flush=True)
if name == "vanilla harnesses":
# Stream the runner's own progress; it keeps per-harness logs.
run_id = uuid.uuid4().hex
subprocess.run(command, cwd=ROOT, env=dict(os.environ, PARITY_RUN_ID=run_id))
summary = ROOT / ".local/parity-runner/last-run.json"
finished = json.loads(summary.read_text()) if summary.exists() else {}
if finished.get("run") != run_id:
print("tools/parity.py stopped before finishing its run")
status = 1
else:
known = set(filter(None, args.known_failures.split(",")))
failing = set(finished["failed"])
new = sorted(failing - known)
if failing:
print(f"Failing harnesses: {', '.join(sorted(failing))}; new: {', '.join(new) or 'none'}")
status = 1 if new else 0
else:
with log.open("w") as stream:
status = subprocess.run(command, cwd=ROOT, stdout=stream, stderr=subprocess.STDOUT).returncode
seconds = round(time.monotonic() - started)
results.append({"step": name, "passed": status == 0, "seconds": seconds})
if status:
passed = False
print(f"FAILED ({seconds}s)")
if name != "vanilla harnesses":
print("".join(log.read_text(errors="replace").splitlines(keepends=True)[-40:]))
print(f"Full log: {log}")
break
print(f"ok ({seconds}s)")
RESULT.write_text(json.dumps({"commit": commit, "dirty": dirty, "passed": passed, "quick": args.quick,
"parity": not (args.quick or args.no_parity), "steps": results,
"finished": time.strftime("%Y-%m-%dT%H:%M:%S")}, indent=1))
print("Gate passed." if passed else "Gate failed.")
return 0 if passed else 1
if __name__ == "__main__":
sys.exit(main())
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""Generate crates/horizon-client/src/lan/command_suggestions.rs: the argument
nodes of vanilla's command tree that have a custom suggestion provider, and
the provider's network name (ClientboundCommandsPacket sends it; the commands
report does not). The list comes from VanillaCommandSuggestionsExporter run
against the pinned client jar:
javac --release 25 -proc:none -sourcepath mods/horizon/src/test/java -cp CLIENT_CP \\
-d BUILD mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandSuggestionsExporter.java
java -cp BUILD:CLIENT_CP dev.horizonlab.parity.VanillaCommandSuggestionsExporter suggestions.tsv
generate_command_suggestions.py suggestions.tsv
"""
import argparse
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("tsv", type=Path)
parser.add_argument("--out", type=Path, default=ROOT / "crates/horizon-client/src/lan/command_suggestions.rs")
args = parser.parse_args()
rows = sorted(tuple(line.split("\t")) for line in args.tsv.read_text().splitlines() if line.strip())
if len(rows) < 50:
raise SystemExit(f"only {len(rows)} nodes")
lines = [
"//! Argument nodes of vanilla's command tree with a custom suggestion",
"//! provider (path of node names from the root, provider network name).",
"//! Generated by tools/generate_command_suggestions.py from",
"//! VanillaCommandSuggestionsExporter; do not edit by hand.",
"",
"pub const SUGGESTIONS: &[(&str, &str)] = &[",
]
lines += [f' ("{path}", "{provider}"),' for path, provider in rows]
lines += ["];", ""]
args.out.write_text("\n".join(lines))
print(f"wrote {len(rows)} nodes to {args.out}")
if __name__ == "__main__":
main()
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Generate crates/horizon-client/src/lan/tracking.rs: every entity type's
tracking settings (EntityType.Builder clientTrackingRange, updateInterval and
trackDeltas, which ChunkMap.TrackedEntity and ServerEntity use to decide who
sees an entity and how often its movement is sent), read from the decompiled
EntityTypes.java.
generate_entity_tracking.py [--sources .local/minecraft/26.3/sources/client]
"""
import argparse
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
INT_MAX = 2147483647
def parse(sources):
text = (sources / "net/minecraft/world/entity/EntityTypes.java").read_text()
out = []
for m in re.finditer(r"public static final EntityType<[\w.]+> (\w+) = register\((.*?)\n \);", text, re.S):
name, body = m.group(1).lower(), m.group(2)
range_ = re.findall(r"\.clientTrackingRange\((\d+)\)", body)
interval = re.findall(r"\.updateInterval\((\w+(?:\.\w+)?)\)", body)
track = ".dontTrackDeltas()" not in body
r = int(range_[-1]) if range_ else 5
if ".noUpdateInterval()" in body or (interval and interval[-1] == "Integer.MAX_VALUE"):
i = 0
else:
i = int(interval[-1]) if interval else 3
out.append((f"minecraft:{name}", r, i, track))
return sorted(out)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--sources", type=Path, default=ROOT / ".local/minecraft/26.3/sources/client")
parser.add_argument("--out", type=Path, default=ROOT / "crates/horizon-client/src/lan/tracking.rs")
args = parser.parse_args()
rows = parse(args.sources)
if len(rows) < 100:
raise SystemExit(f"only {len(rows)} entity types found")
lines = [
"//! Entity tracking settings per entity type (EntityType.Builder",
"//! clientTrackingRange in chunks, updateInterval in ticks with 0 for never,",
"//! trackDeltas). Generated by tools/generate_entity_tracking.py from the",
"//! decompiled EntityTypes.java; do not edit by hand.",
"",
"/// (entity type, tracking range in chunks, update interval, track deltas), sorted.",
"pub const TRACKING: &[(&str, u8, u32, bool)] = &[",
]
lines += [f' ("{n}", {r}, {i}, {str(t).lower()}),' for n, r, i, t in rows]
lines += [
"];",
"",
"/// The settings of one entity type; unknown types get the builder defaults.",
"pub fn settings(kind: &str) -> (u8, u32, bool) {",
" TRACKING",
" .binary_search_by(|row| row.0.cmp(kind))",
" .map_or((5, 3, true), |i| (TRACKING[i].1, TRACKING[i].2, TRACKING[i].3))",
"}",
"",
]
args.out.write_text("\n".join(lines))
print(f"wrote {len(rows)} entity types to {args.out}")
if __name__ == "__main__":
main()
+6
View File
@@ -6,6 +6,7 @@ from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import re
import shutil
@@ -21,6 +22,11 @@ LOCAL = ROOT / ".local"
LOCK = ROOT / "research-lock.json"
def cargo_target():
"""Cargo's target directory, honouring CARGO_TARGET_DIR (tools/parity.py sets it)."""
return ROOT / os.environ.get("CARGO_TARGET_DIR", "target")
def write_json(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
+284
View File
@@ -0,0 +1,284 @@
#!/usr/bin/env python3
"""A decoding TCP proxy for the Minecraft 26.3 protocol (offline mode, no
encryption): clients connect to LISTEN, it forwards to TARGET and records
every packet in both directions as JSON lines (time, direction, state, id,
name, size and the payload), following the connection state through the
handshake, login, configuration and play (and back to configuration).
net_capture.py --listen 25570 --target localhost:25565 --out capture.jsonl
The packet names come from crates/horizon-protocol/src/ids.rs, which is
generated from vanilla's packets report. `summary` prints what a capture
contains, `diff` compares the packet sequences of two captures (for example
Horizon hosting and a vanilla server serving the same world).
"""
import argparse
import json
import re
import socket
import sys
import threading
import time
import zlib
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
STATES = ["handshake", "status", "login", "configuration", "play"]
def load_names(path=ROOT / "crates/horizon-protocol/src/ids.rs"):
"""{(state, direction): [name by id]} from the generated id tables."""
text = path.read_text()
names = {}
for state in STATES:
block = re.search(r"pub mod %s \{(.*?)\n\}" % state, text, re.S)
if not block:
continue
for direction in ("clientbound", "serverbound"):
part = re.search(r"pub mod %s \{.*?NAMES: &\[&str\] = &\[(.*?)\];" % direction,
block.group(1), re.S)
if part:
names[(state, direction)] = re.findall(r'"([^"]+)"', part.group(1))
return names
def read_varint(data, pos):
value = shift = 0
while True:
if pos >= len(data):
raise IndexError("truncated varint")
b = data[pos]
pos += 1
value |= (b & 0x7F) << shift
shift += 7
if not b & 0x80:
if value & 0x80000000:
value -= 1 << 32
return value, pos
if shift > 35:
raise ValueError("varint too long")
class Session:
"""The state both directions of one connection share."""
def __init__(self, conn_id, out, names, lock, full):
self.id = conn_id
self.state = {"clientbound": "handshake", "serverbound": "handshake"}
self.threshold = -1
self.out = out
self.names = names
self.lock = lock
self.full = full
self.start = time.time()
self.closed = threading.Event()
def name(self, direction, packet_id):
table = self.names.get((self.state[direction], direction), [])
return table[packet_id] if 0 <= packet_id < len(table) else f"unknown_{packet_id}"
def record(self, direction, packet_id, payload):
state = self.state[direction]
name = self.name(direction, packet_id)
entry = {
"conn": self.id,
"t": round(time.time() - self.start, 4),
"dir": "s2c" if direction == "clientbound" else "c2s",
"state": state,
"id": packet_id,
"name": name,
"size": len(payload),
}
if self.full or len(payload) <= 4096:
entry["data"] = payload.hex()
else:
entry["head"] = payload[:512].hex()
with self.lock:
self.out.write(json.dumps(entry) + "\n")
self.out.flush()
self.transition(direction, name, payload)
def transition(self, direction, name, payload):
s = self.state
if direction == "serverbound":
if s["serverbound"] == "handshake" and name == "intention":
pos = read_varint(payload, 0)[1]
length, pos = read_varint(payload, pos)
intent = read_varint(payload, pos + length + 2)[0]
nxt = {1: "status", 2: "login", 3: "login"}.get(intent, "login")
s["serverbound"] = s["clientbound"] = nxt
elif s["serverbound"] == "login" and name == "login_acknowledged":
s["serverbound"] = s["clientbound"] = "configuration"
elif s["serverbound"] == "configuration" and name == "finish_configuration":
s["serverbound"] = s["clientbound"] = "play"
elif s["serverbound"] == "play" and name == "configuration_acknowledged":
s["serverbound"] = s["clientbound"] = "configuration"
elif s["clientbound"] == "login" and name == "login_compression":
self.pending_threshold = read_varint(payload, 0)[0]
class Pipe(threading.Thread):
def __init__(self, session, direction, src, dst):
super().__init__(daemon=True)
self.session, self.direction, self.src, self.dst = session, direction, src, dst
def run(self):
buffer = b""
s = self.session
try:
while True:
chunk = self.src.recv(1 << 16)
if not chunk:
break
buffer += chunk
frames = []
while True:
try:
length, pos = read_varint(buffer, 0)
except IndexError:
break
if len(buffer) < pos + length:
break
frames.append(buffer[:pos + length])
body, buffer = buffer[pos:pos + length], buffer[pos + length:]
threshold = s.threshold
if threshold >= 0:
size, p = read_varint(body, 0)
body = zlib.decompress(body[p:]) if size else body[p:]
packet_id, p = read_varint(body, 0)
s.record(self.direction, packet_id, body[p:])
# The compression threshold applies after its packet, in
# both directions; the client answers only after reading it.
pending = getattr(s, "pending_threshold", None)
if pending is not None:
s.threshold = pending
s.pending_threshold = None
# State switches must be in effect before the peer can
# answer, so forward each frame after recording it.
self.dst.sendall(frames.pop())
except (OSError, ValueError, zlib.error) as e:
with s.lock:
s.out.write(json.dumps({"conn": s.id, "event": "error", "dir": self.direction,
"error": str(e)}) + "\n")
s.out.flush()
finally:
for sock in (self.src, self.dst):
try:
sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
s.closed.set()
def serve(listen, target, out_path, full=False, ready=None, stop=None):
names = load_names()
host, port = target.rsplit(":", 1)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(("127.0.0.1", listen))
server.listen()
server.settimeout(0.5)
lock = threading.Lock()
conn_id = 0
with open(out_path, "a") as out:
if ready:
ready.set()
while not (stop and stop.is_set()):
try:
client, _ = server.accept()
except socket.timeout:
continue
conn_id += 1
try:
upstream = socket.create_connection((host, int(port)))
except OSError as e:
client.close()
with lock:
out.write(json.dumps({"conn": conn_id, "event": "error",
"error": f"upstream: {e}"}) + "\n")
continue
for sock in (client, upstream):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
session = Session(conn_id, out, names, lock, full)
Pipe(session, "serverbound", client, upstream).start()
Pipe(session, "clientbound", upstream, client).start()
server.close()
def start_background(listen, target, out_path, full=False):
"""Run the proxy on a thread; returns the stop event."""
ready, stop = threading.Event(), threading.Event()
threading.Thread(target=serve, args=(listen, target, out_path, full, ready, stop),
daemon=True).start()
ready.wait(5)
return stop
def load(path):
return [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
def play_sessions(entries):
"""Connections that reached the play state."""
return sorted({e["conn"] for e in entries if e.get("state") == "play"})
def summary(entries, conn=None):
lines = []
conns = [conn] if conn else sorted({e["conn"] for e in entries})
for c in conns:
mine = [e for e in entries if e["conn"] == c and "name" in e]
lines.append(f"connection {c}: {len(mine)} packets")
counts = Counter((e["dir"], e["state"], e["name"]) for e in mine)
for (d, s, n), k in sorted(counts.items()):
size = sum(e["size"] for e in mine if (e["dir"], e["state"], e["name"]) == (d, s, n))
lines.append(f" {d} {s:13} {n:40} x{k:<6} {size} bytes")
for e in entries:
if e["conn"] == c and e.get("event") == "error":
lines.append(f" error ({e.get('dir')}): {e['error']}")
return "\n".join(lines)
def sequence(entries, conn, direction="s2c", until="player_position"):
"""Packet names in order, up to and including the first `until`."""
out = []
for e in entries:
if e["conn"] != conn or e.get("dir") != direction or "name" not in e:
continue
out.append(f"{e['state']}/{e['name']}")
if e["name"] == until and e["state"] == "play":
break
return out
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="command", required=True)
p = sub.add_parser("proxy")
p.add_argument("--listen", type=int, required=True)
p.add_argument("--target", required=True)
p.add_argument("--out", type=Path, required=True)
p.add_argument("--full", action="store_true", help="keep every payload in full")
s = sub.add_parser("summary")
s.add_argument("capture", type=Path)
d = sub.add_parser("diff")
d.add_argument("a", type=Path)
d.add_argument("b", type=Path)
d.add_argument("--until", default="player_position")
args = parser.parse_args()
if args.command == "proxy":
serve(args.listen, args.target, args.out, args.full)
elif args.command == "summary":
print(summary(load(args.capture)))
else:
import difflib
a, b = load(args.a), load(args.b)
sa = sequence(a, play_sessions(a)[0], until=args.until)
sb = sequence(b, play_sessions(b)[0], until=args.until)
sys.stdout.writelines(difflib.unified_diff([x + "\n" for x in sa], [x + "\n" for x in sb],
str(args.a), str(args.b)))
if __name__ == "__main__":
main()
+526
View File
@@ -0,0 +1,526 @@
#!/usr/bin/env python3
"""Run the vanilla differential harnesses (tools/test_*_parity.py) quickly.
python3 tools/parity.py # harnesses whose inputs changed, or that never passed
python3 tools/parity.py --all # every harness, from scratch (the audit)
python3 tools/parity.py --fresh ... # don't reuse vanilla oracle results
python3 tools/parity.py food light # these harnesses (names without test_/_parity.py)
python3 tools/parity.py --failed # the ones that failed last time
python3 tools/parity.py --list # what would run, without running it
python3 tools/parity.py --status # last result of every harness
Each harness runs unmodified, in parallel, under a tracer that records what it
read: its Python modules, Java oracle sources, other repository files, and the
Rust sources of every probe it executed (from Cargo's dep-info). A harness
reruns only when one of those files, the pinned vanilla artifacts or the
toolchains change; otherwise its last pass stands.
Vanilla oracles are reused too: tools/parity_shim.py stands in for java and
javac and replays an oracle run whose inputs are unchanged, so a Rust-only
change costs only the Rust side. A harness that fails while reusing oracle
results is rerun fresh, and stops reusing them if it then passes. --all and
--fresh never reuse them.
Harness probes build into .local/parity-target with release optimisations but
without LTO and with 16 codegen units (`PROFILE` below), which builds in
seconds instead of minutes. Rust does not let those settings change results:
there is no fast-math, and overflow checks stay as in release. Probes built in
the dev profile are optimised too, keeping their overflow checks. Probes the
recorded harnesses need are built in one Cargo run before the harnesses start,
so parallel harnesses don't queue on Cargo's lock.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
LOCAL = ROOT / ".local"
STATE_DIR = LOCAL / "parity-runner"
STATE = STATE_DIR / "state.json"
TARGET = LOCAL / "parity-target"
PROFILE = {
"CARGO_PROFILE_RELEASE_LTO": "false",
"CARGO_PROFILE_RELEASE_CODEGEN_UNITS": "16",
"CARGO_PROFILE_RELEASE_INCREMENTAL": "true",
# Probes built in the dev profile keep its overflow checks and debug
# assertions, but run optimised.
"CARGO_PROFILE_DEV_OPT_LEVEL": "3",
}
SHIM = STATE_DIR / "shim"
# Results shared by every worktree using the same vanilla data (.local/minecraft
# links to a shared directory in parallel worktrees): passes keyed by content,
# so a harness whose inputs match one that passed elsewhere doesn't run again.
SHARED = Path(os.environ.get("PARITY_SHARED") or (LOCAL / "minecraft").resolve().parent / "parity-shared")
MACHINE_JOBS = int(os.environ.get("PARITY_MACHINE_JOBS") or max(1, (os.cpu_count() or 4) // 2))
DEFAULT_MEMORY = 3 << 30 # assumed peak for a harness that never ran here
def harnesses():
return {path.name[len("test_"):-len("_parity.py")]: path for path in sorted((ROOT / "tools").glob("test_*_parity.py"))}
def load_state():
return json.loads(STATE.read_text()) if STATE.exists() else {"harnesses": {}, "hashes": {}}
def save_state(state):
STATE_DIR.mkdir(parents=True, exist_ok=True)
temporary = STATE.with_suffix(".tmp")
temporary.write_text(json.dumps(state, indent=1, sort_keys=True))
temporary.replace(STATE)
class Hasher:
"""Content hashes, reused while a file's size and mtime stay the same."""
def __init__(self, cache):
self.cache = cache
def __call__(self, path):
try:
stat = os.stat(path)
except FileNotFoundError:
return "missing"
stamp = [stat.st_size, stat.st_mtime_ns]
cached = self.cache.get(str(path))
if cached and cached[0] == stamp:
return cached[1]
with open(path, "rb") as stream:
digest = hashlib.file_digest(stream, "sha256").hexdigest()
self.cache[str(path)] = [stamp, digest]
return digest
def environment_key(hasher):
"""Everything outside the recorded dependencies that can change a result."""
def version(command):
try:
result = subprocess.run(command, capture_output=True, text=True, cwd=ROOT)
return (result.stdout + result.stderr).strip()
except FileNotFoundError:
return "missing"
lock = json.loads((ROOT / "research-lock.json").read_text())
version_dir = LOCAL / "minecraft" / lock["minecraft"]["version"]
parts = [version(["rustc", "-V"]), version(["java", "-version"]), version(["javac", "-version"]),
json.dumps(PROFILE, sort_keys=True), hasher(ROOT / "research-lock.json"), hasher(ROOT / "Cargo.lock"),
hasher(version_dir / "prepared.json"), hasher(version_dir / "manifest.json")]
return hashlib.sha256("\n".join(parts).encode()).hexdigest()
def key(record, hasher, environment):
digest = hashlib.sha256(environment.encode())
for path in sorted(record["dependencies"]):
digest.update(f"{path}\0{hasher(ROOT / path)}\n".encode())
return digest.hexdigest()
def inside(path, root):
try:
Path(path).resolve().relative_to(root)
return True
except (ValueError, OSError):
return False
def dep_info(binary):
"""Source files Cargo recorded for a built binary (its .d file, spaces escaped as "\\ ")."""
info = Path(str(binary) + ".d")
if not info.exists():
return []
sources = []
for line in info.read_text().splitlines():
_, separator, rest = line.partition(": ")
if separator:
sources += [part.replace("\\ ", " ") for part in re.split(r"(?<!\\) ", rest.strip()) if part]
return sources
def artifact_path(kind, name, profile):
directory = "debug" if profile == "dev" else profile
return TARGET / directory / ("examples" if kind == "example" else "") / name
def artifacts_of(arguments):
"""The [kind, name, profile] targets a cargo build/run command line names."""
arguments = arguments[:arguments.index("--")] if "--" in arguments else arguments
profile = "release" if "--release" in arguments else "dev"
if "--profile" in arguments:
profile = arguments[arguments.index("--profile") + 1]
found = []
for flag, kind in (("--example", "example"), ("--bin", "bin")):
for index, argument in enumerate(arguments[:-1]):
if argument == flag:
found.append([kind, arguments[index + 1], profile])
return found
def dependencies(trace):
"""Repository files a traced harness depended on, relative to ROOT."""
found = set(trace["modules"])
found.update(trace["read"])
artifacts = []
for arguments in trace["commands"]:
program = Path(arguments[0]).name if arguments else ""
if program == "cargo" and ("build" in arguments or "run" in arguments):
artifacts += artifacts_of(arguments)
if arguments and inside(arguments[0], TARGET):
found.update(dep_info(Path(arguments[0])))
if program == "javac":
found.update(java_sources(arguments))
for argument in arguments[1:]:
if isinstance(argument, str) and os.path.isfile(argument):
found.add(argument)
for kind, name, profile in artifacts:
found.update(dep_info(artifact_path(kind, name, profile)))
kept = set()
for path in found:
path = Path(path) if os.path.isabs(path) else ROOT / path
if inside(path, ROOT) and not inside(path, LOCAL) and not inside(path, ROOT / "target") and path.is_file():
kept.add(str(path.resolve().relative_to(ROOT)))
unique = []
for artifact in artifacts:
if artifact not in unique:
unique.append(artifact)
return sorted(kept), unique
def java_sources(arguments):
"""Java files javac compiled: the named ones, plus those it pulled from -sourcepath into -d."""
sources = [argument for argument in arguments if str(argument).endswith(".java")]
if "-d" in arguments and "-sourcepath" in arguments:
output = Path(arguments[arguments.index("-d") + 1])
source_roots = arguments[arguments.index("-sourcepath") + 1].split(os.pathsep)
for compiled in output.rglob("*.class") if output.is_dir() else []:
relative = compiled.relative_to(output).with_suffix("")
top = relative.with_name(relative.name.split("$")[0] + ".java")
for root in source_roots:
if (Path(root) / top).is_file():
sources.append(str(Path(root) / top))
return sources
def run_environment(reuse_oracles=False):
environment = dict(os.environ, CARGO_TARGET_DIR=str(TARGET), PYTHONDONTWRITEBYTECODE="1", HORIZON_NO_AUDIO="1", **PROFILE)
environment.pop("CARGO_BUILD_JOBS", None)
if reuse_oracles:
# tools/parity_shim.py stands in for java and javac and replays unchanged oracle runs.
SHIM.mkdir(parents=True, exist_ok=True)
for name in ("java", "javac"):
link = SHIM / name
if not link.is_symlink():
link.symlink_to(ROOT / "tools" / "parity_shim.py")
environment.update(PARITY_SHIM_REAL_PATH=os.environ.get("PATH", ""), PARITY_SHIM_CACHE=str(STATE_DIR / "oracle-cache"),
PATH=f"{SHIM}{os.pathsep}{os.environ.get('PATH', '')}")
return environment
def prebuild(artifacts, jobs):
"""Build every recorded probe in one Cargo run so harnesses don't serialise on its lock."""
environment = run_environment()
environment["CARGO_BUILD_JOBS"] = str(jobs)
errors = ""
for profile in sorted({profile for _, _, profile in artifacts}):
command = ["cargo", "build", "--locked", "--workspace", "--profile", profile]
for kind, name, _ in (artifact for artifact in artifacts if artifact[2] == profile):
command += ["--examples", "--bins"] if kind == "all" else [f"--{kind}", name]
result = subprocess.run(command, cwd=ROOT, env=environment, capture_output=True, text=True)
if result.returncode:
errors += result.stderr
return not errors, errors
LARGE_OUTPUT = 64 << 20
OWN_DIRECTORIES = {"parity-target", "parity-runner", "rea", "logs", "gate"}
def outputs_listing(name, fresh=False):
path = STATE_DIR / "oracle-outputs" / f"{name}.txt"
path.parent.mkdir(parents=True, exist_ok=True)
if fresh:
path.write_text("")
return path
def clear_large_outputs(name, trace):
"""After a pass, delete the large files a harness regenerates on every run.
Harness outputs reach gigabytes and used to stay in every worktree. Vanilla
oracle outputs are kept, since reusing an oracle run needs them in place;
everything else large under the harness's .local directories is rebuilt on
its next run."""
local = LOCAL.resolve()
keep = {os.path.realpath(line) for line in outputs_listing(name).read_text().splitlines() if line}
directories = set()
for command in trace["commands"]:
for argument in command[1:]:
path = Path(os.path.realpath(argument if os.path.isabs(argument) else ROOT / argument))
try:
top = path.relative_to(local).parts[0]
except (ValueError, IndexError):
continue
if top not in OWN_DIRECTORIES:
directories.add(local / top)
for directory in directories:
for file in (directory.rglob("*") if directory.is_dir() else []):
try:
if file.is_file() and not file.is_symlink() and file.stat().st_size >= LARGE_OUTPUT and str(file) not in keep:
file.unlink()
except OSError:
pass
def publish(name, record):
"""Share a pass, so any worktree with the same inputs can reuse it."""
if record["status"] != "pass" or "key" not in record:
return
for path, data in ((SHARED / "passes" / name / f"{record['key']}.json", record),
(SHARED / "dependencies" / f"{name}.json", {k: record[k] for k in ("dependencies", "artifacts")})):
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
temporary.write_text(json.dumps(data))
temporary.replace(path)
def machine_slot():
"""One of MACHINE_JOBS lock files shared by every runner on this machine, or None if all are taken."""
import fcntl
slots = SHARED / "slots"
slots.mkdir(parents=True, exist_ok=True)
for index in range(MACHINE_JOBS):
handle = open(slots / f"{index}.lock", "w")
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
return handle
except OSError:
handle.close()
return None
def memory_available():
for line in Path("/proc/meminfo").read_text().splitlines():
if line.startswith("MemAvailable:"):
return int(line.split()[1]) * 1024
return 16 << 30
def run(selected, state, hasher, environment_digest, jobs, timeout, memory_budget, reuse_oracles):
logs = STATE_DIR / "logs"
traces = STATE_DIR / "traces"
logs.mkdir(parents=True, exist_ok=True)
traces.mkdir(parents=True, exist_ok=True)
records = state["harnesses"]
# Longest first, so the slow harnesses don't start last.
queue = sorted(selected, key=lambda name: -records.get(name, {}).get("seconds", 1e9))
running = {}
results = {}
retried = set()
started_all = time.monotonic()
while queue or running:
in_use = sum(item[3] for item in running.values())
for name in list(queue):
if len(running) >= jobs:
break
expected = records.get(name, {}).get("peak_bytes", DEFAULT_MEMORY)
if running and in_use + expected > memory_budget:
continue
slot = machine_slot()
if slot is None:
break # other runners on this machine hold every slot
queue.remove(name)
reuse = reuse_oracles and records.get(name, {}).get("oracle_reuse", True) and name not in retried
trace = traces / f"{name}.json"
trace.unlink(missing_ok=True)
log = (logs / f"{name}.log").open("w")
environment = run_environment(reuse)
environment["PARITY_SHIM_OUTPUTS"] = str(outputs_listing(name, fresh=True))
process = subprocess.Popen(
[sys.executable, str(Path(__file__)), "--trace", str(trace), str(selected[name])],
cwd=ROOT, env=environment, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
running[name] = (process, time.monotonic(), log, expected, reuse, slot)
in_use += expected
time.sleep(0.2)
for name, (process, started, log, _, reused, slot) in list(running.items()):
elapsed = time.monotonic() - started
if process.poll() is None and elapsed < timeout:
continue
if process.poll() is None:
os.killpg(process.pid, 9)
process.wait()
print(f"--- {name}: timed out after {timeout}s", file=log)
log.close()
slot.close()
del running[name]
passed = process.returncode == 0
if not passed and reused and records.get(name, {}).get("status") != "fail":
# A new failure might come from a reused oracle result: run it again from scratch.
retried.add(name)
queue.insert(0, name)
print(f"retry {name} without reused oracle results", flush=True)
continue
trace_path = traces / f"{name}.json"
record = {"status": "pass" if passed else "fail", "seconds": round(elapsed, 1),
"finished": time.strftime("%Y-%m-%dT%H:%M:%S")}
# A harness that only passes fresh no longer reuses oracle results.
record["oracle_reuse"] = records.get(name, {}).get("oracle_reuse", True) and not (passed and name in retried)
try:
trace = json.loads(trace_path.read_text())
except (OSError, ValueError):
trace = None # killed before writing it, or the disk was full: the pass can't be keyed
if trace:
record["dependencies"], record["artifacts"] = dependencies(trace)
record["peak_bytes"] = trace["peak_bytes"]
record["key"] = key(record, hasher, environment_digest)
if passed:
clear_large_outputs(name, trace)
else:
record["dependencies"], record["artifacts"] = [], []
records[name] = record
results[name] = record
save_state(state)
publish(name, record)
tail = "" if passed else f" ({logs / (name + '.log')})"
print(f"{'PASS' if passed else 'FAIL'} {name} {elapsed:.0f}s{tail}", flush=True)
return results, time.monotonic() - started_all
def stale(name, state, hasher, environment):
record = state["harnesses"].get(name)
if record and record.get("status") == "pass" and "key" in record and key(record, hasher, environment) == record["key"]:
return False
# Passed elsewhere with the same inputs? Try this worktree's and the shared dependency lists.
candidates = [record] if record and record.get("dependencies") else []
template = SHARED / "dependencies" / f"{name}.json"
if template.exists():
candidates.append(json.loads(template.read_text()))
for candidate in candidates:
shared = SHARED / "passes" / name / f"{key(candidate, hasher, environment)}.json"
if shared.exists():
state["harnesses"][name] = dict(json.loads(shared.read_text()), shared=True)
return False
return True
def trace_main(output, script, arguments):
"""Run one harness and record what it read and executed."""
import atexit
import resource
import runpy
read, commands = set(), []
def audit(event, details):
if event == "open":
path, mode = details[0], details[1]
if isinstance(path, (str, bytes, os.PathLike)) and (mode is None or "r" in str(mode) and "+" not in str(mode)):
read.add(os.fsdecode(path))
elif event == "subprocess.Popen":
arguments_ = details[1]
arguments_ = [arguments_] if isinstance(arguments_, (str, bytes, os.PathLike)) else list(arguments_ or [])
commands.append([os.fsdecode(a) if isinstance(a, (bytes, os.PathLike)) else str(a) for a in arguments_])
def write():
modules = [getattr(module, "__file__", None) for module in list(sys.modules.values())]
peak = max(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss)
Path(output).write_text(json.dumps({
"modules": sorted({m for m in modules if m and inside(m, ROOT)}),
"read": sorted(path for path in read if os.path.isabs(path) or not path.startswith("<")),
"commands": commands,
"peak_bytes": peak * 1024,
}))
atexit.register(write)
sys.addaudithook(audit)
sys.argv = [script, *arguments]
sys.path.insert(0, str(Path(script).parent))
runpy.run_path(script, run_name="__main__")
def finished_run(failed):
"""Record that this run completed, for tools/gate.py: a crashed runner never writes it."""
STATE_DIR.mkdir(parents=True, exist_ok=True)
(STATE_DIR / "last-run.json").write_text(json.dumps({"run": os.environ.get("PARITY_RUN_ID"), "failed": failed}))
def main():
if len(sys.argv) > 1 and sys.argv[1] == "--trace":
return trace_main(sys.argv[2], sys.argv[3], sys.argv[4:])
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("names", nargs="*", help="harness names, e.g. food or block_update")
parser.add_argument("--all", action="store_true", help="run every harness from scratch, ignoring earlier passes")
parser.add_argument("--fresh", action="store_true", help="run the vanilla oracles even if their inputs are unchanged")
parser.add_argument("--failed", action="store_true", help="rerun the harnesses that failed last time")
parser.add_argument("--list", action="store_true", help="print what would run, then stop")
parser.add_argument("--status", action="store_true", help="print each harness's last result")
parser.add_argument("-j", "--jobs", type=int, default=max(1, (os.cpu_count() or 4) // 3),
help="harnesses at once in this run; every runner on the machine shares PARITY_MACHINE_JOBS slots")
parser.add_argument("--timeout", type=int, default=3600, help="seconds per harness")
args = parser.parse_args()
found = harnesses()
state = load_state()
hasher = Hasher(state["hashes"])
environment = environment_key(hasher)
records = state["harnesses"]
unknown = [name for name in args.names if name not in found]
if unknown:
parser.error("unknown harnesses: " + ", ".join(unknown))
if args.status:
for name in found:
record = records.get(name)
status = "never run" if not record else record["status"] + (" (stale)" if stale(name, state, hasher, environment) and record["status"] == "pass" else "")
seconds = f"{record['seconds']:>7.0f}s" if record else ""
print(f"{name:<40} {status:<15} {seconds}")
save_state(state)
return 0
if args.names:
chosen = args.names
elif args.all:
chosen = list(found)
elif args.failed:
chosen = [name for name in found if records.get(name, {}).get("status") == "fail"]
else:
chosen = [name for name in found if stale(name, state, hasher, environment)]
selected = {name: found[name] for name in chosen}
if args.list or not selected:
for name in selected:
print(name)
print(f"{len(selected)} of {len(found)} harnesses would run" if args.list else "Nothing to run: every harness passed with its current inputs.")
save_state(state)
if not args.list:
finished_run([])
return 0
jobs = max(1, args.jobs)
# Harnesses that never ran here have no recorded probes: build them all.
artifacts = [["all", "", "release"]] if any("artifacts" not in records.get(name, {}) for name in selected) else []
for name in selected:
for artifact in records.get(name, {}).get("artifacts", []):
if artifact not in artifacts:
artifacts.append(artifact)
print("Building probes...", flush=True)
started = time.monotonic()
built, errors = prebuild(artifacts, os.cpu_count() or 8)
if not built:
print(errors[-4000:])
print("Probe build failed; harnesses will report their own build errors.", flush=True)
print(f"Probes built in {time.monotonic() - started:.0f}s. Running {len(selected)} harnesses, {jobs} at a time...", flush=True)
reuse_oracles = not (args.fresh or args.all)
results, elapsed = run(selected, state, hasher, environment_key(hasher), jobs, args.timeout, int(memory_available() * 0.75),
reuse_oracles)
save_state(state)
failed = sorted(name for name, record in results.items() if record["status"] != "pass")
finished_run(failed)
print(f"\n{len(results) - len(failed)} passed, {len(failed)} failed in {elapsed / 60:.1f} min.")
for name in failed:
print(f" {name}: {STATE_DIR / 'logs' / (name + '.log')}")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
+200
View File
@@ -0,0 +1,200 @@
#!/usr/bin/env python3
"""Reuse a vanilla oracle's last results when nothing it reads has changed.
tools/parity.py puts `java` and `javac` links to this script first on PATH.
A run is identified by its command line, stdin when it is a file, and the
real program. After a successful run, the files it created or changed under
the paths its arguments name (classpath and sourcepath entries included) are
recorded as its outputs, with their size and mtime and its stdout and stderr;
every other file under those paths is recorded as an input with its content
hash. The next run of the same command replays the recorded output instead
of running the oracle if every input has the same content, no file was added
beside them, and the outputs are exactly as it left them. On a Rust-only
change a harness then pays only for its Rust side.
Files an oracle writes outside its named paths are not tracked. A harness
that depends on them fails on reuse; tools/parity.py then reruns it fresh and
stops reusing its oracle results.
A run that reads stdin from a pipe, or fails, is never cached.
PARITY_JAVA_CACHE=0 disables reuse (tools/parity.py --fresh).
"""
import hashlib
import json
import os
from pathlib import Path
import shutil
import sqlite3
import subprocess
import sys
import threading
CACHE = Path(os.environ.get("PARITY_SHIM_CACHE", ".local/parity-runner/oracle-cache"))
PATH_OPTIONS = {"-cp", "-classpath", "--class-path", "-sourcepath", "--source-path", "-p", "--module-path"}
def real(name):
found = shutil.which(name, path=os.environ.get("PARITY_SHIM_REAL_PATH", ""))
if not found:
sys.exit(f"parity shim: no real {name} on PARITY_SHIM_REAL_PATH")
return found
class Hashes:
"""Content hashes keyed by path, size and mtime, shared by parallel harnesses."""
def __init__(self):
CACHE.mkdir(parents=True, exist_ok=True)
self.db = sqlite3.connect(CACHE / "hashes.sqlite", timeout=60)
self.db.execute("pragma journal_mode=wal")
self.db.execute("create table if not exists hashes (path text primary key, size int, mtime int, sha text)")
def file(self, path):
stat = os.stat(path)
row = self.db.execute("select size, mtime, sha from hashes where path = ?", (path,)).fetchone()
if row and row[0] == stat.st_size and row[1] == stat.st_mtime_ns:
return row[2]
with open(path, "rb") as stream:
sha = hashlib.file_digest(stream, "sha256").hexdigest()
self.db.execute("insert or replace into hashes values (?, ?, ?, ?)", (path, stat.st_size, stat.st_mtime_ns, sha))
self.db.commit()
return sha
def tree(root):
for directory, _, files in os.walk(root):
for name in files:
yield os.path.join(directory, name)
def named_paths(arguments):
"""Every filesystem path the arguments name, with classpath lists split."""
paths = []
for index, argument in enumerate(arguments):
if index and arguments[index - 1] in PATH_OPTIONS:
paths += [entry for entry in argument.split(os.pathsep) if entry]
elif argument.startswith("-D") and "=" in argument:
paths.append(argument.split("=", 1)[1])
elif not argument.startswith("-"):
paths.append(argument)
return [os.path.abspath(path) for path in paths if path]
def snapshot(paths):
state = {}
for path in paths:
files = tree(path) if os.path.isdir(path) else [path]
for file in files:
try:
stat = os.stat(file)
state[file] = [stat.st_size, stat.st_mtime_ns]
except FileNotFoundError:
state[file] = None
return state
def stdin_identity(hashes):
try:
stat = os.fstat(0)
except OSError:
return "closed"
if os.path.samestat(stat, os.stat(os.devnull)) if os.path.exists(os.devnull) else False:
return "null"
import stat as modes
if modes.S_ISREG(stat.st_mode):
return "f:" + hashes.file(os.readlink("/proc/self/fd/0"))
if modes.S_ISCHR(stat.st_mode):
return "tty"
return None # a pipe or socket: its content is unknown, so never cache
def run_and_tee(command):
"""Run the real program, forwarding and recording its stdout and stderr."""
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
captured = {"stdout": bytearray(), "stderr": bytearray()}
def pump(source, sink, buffer):
for chunk in iter(lambda: source.read1(65536), b""):
buffer += chunk
sink.write(chunk)
sink.flush()
threads = [threading.Thread(target=pump, args=(process.stdout, sys.stdout.buffer, captured["stdout"])),
threading.Thread(target=pump, args=(process.stderr, sys.stderr.buffer, captured["stderr"]))]
for thread in threads:
thread.start()
status = process.wait()
for thread in threads:
thread.join()
return status, captured
def files_under(paths):
found = set()
for path in paths:
if os.path.isdir(path):
found.update(tree(path))
elif os.path.isfile(path):
found.add(path)
return found
def note_outputs(outputs):
"""Tell tools/parity.py which files are oracle outputs, which it keeps when clearing large outputs."""
listing = os.environ.get("PARITY_SHIM_OUTPUTS")
if listing:
with open(listing, "a") as stream:
stream.writelines(f"{path}\n" for path in outputs)
def reusable(saved, paths, hashes):
"""The recorded inputs are unchanged, nothing was added beside them, and the outputs are as left."""
outputs = saved["outputs"]
if files_under(paths) - set(outputs) != set(saved["inputs"]):
return False
if any(snapshot([path]).get(path) != stamp for path, stamp in outputs.items()):
return False
return all(hashes.file(path) == sha for path, sha in saved["inputs"].items())
def main():
name = os.path.basename(sys.argv[0])
arguments = sys.argv[1:]
program = real(name)
if os.environ.get("PARITY_JAVA_CACHE") == "0" or "-version" in arguments or "--version" in arguments:
os.execv(program, [program, *arguments])
hashes = Hashes()
stdin = stdin_identity(hashes)
if stdin is None:
os.execv(program, [program, *arguments])
paths = named_paths(arguments)
command = {"program": os.path.realpath(program), "arguments": arguments, "cwd": os.getcwd(), "stdin": stdin}
key = hashlib.sha256(json.dumps(command, sort_keys=True).encode()).hexdigest()
record = CACHE / f"{key}.json"
saved = json.loads(record.read_text()) if record.exists() else None
if saved and reusable(saved, paths, hashes):
note_outputs(saved["outputs"])
sys.stdout.buffer.write((CACHE / f"{key}.stdout").read_bytes())
sys.stderr.buffer.write((CACHE / f"{key}.stderr").read_bytes())
return 0
before = snapshot(paths)
inputs = {path: hashes.file(path) for path in files_under(paths)}
status, captured = run_and_tee([program, *arguments])
if status != 0:
return status
after = snapshot(paths)
outputs = {path: stamp for path, stamp in after.items() if stamp is not None and before.get(path) != stamp}
for path in outputs:
inputs.pop(path, None)
(CACHE / f"{key}.stdout").write_bytes(captured["stdout"])
(CACHE / f"{key}.stderr").write_bytes(captured["stderr"])
temporary = record.with_suffix(f".{os.getpid()}.tmp")
temporary.write_text(json.dumps({"command": command, "inputs": inputs, "outputs": outputs}))
temporary.replace(record)
note_outputs(outputs)
return 0
if __name__ == "__main__":
sys.exit(main())
+110
View File
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Query the pinned vanilla bytecode through REA (Reverse Engineer Anything).
REA drives a headless JADX over the shipped game JAR, so answers come from the
bytecode Mojang ships rather than from the Vineflower sources: callers through
lambdas and bridges, every overload of a method, and members the decompiled
sources fold away. Prints REA's normalized result as JSON.
python3 tools/rea_vanilla.py classes DispenserBlock
python3 tools/rea_vanilla.py class net.minecraft.world.level.block.DispenserBlock
python3 tools/rea_vanilla.py method net.minecraft.world.level.block.DispenserBlock dispenseFrom
python3 tools/rea_vanilla.py callers net.minecraft.server.level.ServerLevel tickChunk
python3 tools/rea_vanilla.py --jar server-game classes DedicatedServer
The first run downloads the pinned JADX engine into .local/tools/; REA itself
runs from the global `rea` command when it is the pinned version, otherwise
through npx. Needs Node.js 22.19+ and Java 17+.
"""
import argparse
import json
import os
import shutil
import subprocess
import sys
import lab
COMMANDS = {
"classes": ("search-android-classes", ["query"]),
"class": ("inspect-android-class", ["class_name"]),
"method": ("inspect-android-method", ["class_name", "method_name"]),
"callers": ("trace-android-references", ["class_name", "method_name"]),
"refs": ("trace-android-references", ["class_name"]),
}
def engine(lock):
pin = lock["jadx_headless_mcp"]
jar = lab.LOCAL / "tools" / f"jadx-headless-mcp-{pin['version']}-all.jar"
return lab.download(pin["url"], jar, pin["sha256"], "sha256")
def target(game_dir, name):
"""REA admits JADX targets by their .apk name; JADX reads the class files either way."""
source = game_dir / "jars" / f"{name}.jar"
if not source.exists():
raise SystemExit(f"{source} is missing; run python3 tools/prepare_native_client.py --prepare")
copy = lab.LOCAL / "rea" / f"{name}-{lab.digest(source, 'sha256')[:16]}.apk"
if not copy.exists():
copy.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, copy)
return copy
def rea_command(lock):
pin = lock["rea"]
installed = shutil.which("rea")
if installed:
version = subprocess.run([installed, "--version"], capture_output=True, text=True).stdout.strip()
if version == pin["version"]:
return [installed]
return ["npx", "-y", f"{pin['package']}@{pin['version']}"]
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--jar", default="client", choices=["client", "server-game"])
parser.add_argument("--overload-index", type=int)
parser.add_argument("--raw", action="store_true", help="print REA's whole evidence record")
parser.add_argument("command", choices=COMMANDS)
parser.add_argument("arguments", nargs="+")
args = parser.parse_args()
subcommand, names = COMMANDS[args.command]
if len(args.arguments) != len(names):
parser.error(f"{args.command} takes {' '.join(names).upper()}")
lock, game_dir = lab.config()
command = rea_command(lock) + [subcommand, str(target(game_dir, args.jar))]
if args.command in ("callers", "refs"):
command += [args.arguments[0]] + (["--method-name", args.arguments[1]] if args.command == "callers" else [])
else:
command += args.arguments
if args.overload_index is not None:
command += ["--overload-index", str(args.overload_index)]
environment = dict(os.environ, REA_JADX_MCP_JAR=str(engine(lock)))
result = subprocess.run(command + ["--json"], capture_output=True, text=True, env=environment)
try:
record = json.loads(result.stdout)
except json.JSONDecodeError:
sys.stderr.write(result.stdout + result.stderr)
return result.returncode or 1
if "normalized_result" not in record:
details = record.get("details", {})
reasons = [issue["message"] for issue in details.get("issues", [])] or [details.get("reason")]
print(record.get("message"), *filter(None, reasons), sep="\n", file=sys.stderr)
return 1
body = record if args.raw else record["normalized_result"]
if not args.raw:
body.pop("engine", None)
if args.command == "method" and not args.raw and body.get("source", {}).get("text"):
print(f"// {body['class_name']}.{body['method']['reported_signature']}"
f" (overload {body['method']['overload_index']} of {body['overload_count']}, {body['source']['status']})")
print(body["source"]["text"])
else:
print(json.dumps(body, indent=2))
return 0
if __name__ == "__main__":
sys.exit(main())
+5 -2
View File
@@ -36,8 +36,10 @@ FULL = [
('smoker', f'{{{NAME},cooking_total_time:100}}'),
('brewing_stand', f'{{Items:[{{Slot:0b,id:"minecraft:potion",count:1}},{{Slot:3b,id:"minecraft:nether_wart",count:2}},'
'{Slot:4b,id:"minecraft:blaze_powder",count:1}],BrewTime:200,Fuel:10}'),
# The beef must not finish cooking while the scene runs: its item would land
# near the sculk sensors at a time that depends on how long each game ran.
('campfire', '{Items:[{Slot:0b,id:"minecraft:beef",count:1}],CookingTimes:[I;10,0,0,0],'
'CookingTotalTimes:[I;600,0,0,0]}'),
'CookingTotalTimes:[I;60000,0,0,0]}'),
('soul_campfire', ''),
('chiseled_bookshelf', '{Items:[{Slot:0b,id:"minecraft:book",count:1},{Slot:3b,id:"minecraft:book",count:1}],'
'last_interacted_slot:3}'),
@@ -110,7 +112,8 @@ ENTITIES = [
('glow_item_frame', 'Facing:2b'),
('painting', 'Facing:3b,variant:"minecraft:kebab"'),
('arrow', 'inGround:1b,life:5s,damage:2.0d'),
('falling_block', 'BlockState:{id:"minecraft:anvil",properties:{facing:"east"}},Time:3,HurtEntities:1b,FallHurtAmount:2f'),
# Time starts far below 600, after which FallingBlockEntity drops itself as an item.
('falling_block', 'BlockState:{id:"minecraft:anvil",properties:{facing:"east"}},Time:-100000,HurtEntities:1b,FallHurtAmount:2f'),
('tnt', 'fuse:50s,block_state:{id:"minecraft:tnt",properties:{unstable:"true"}}'),
('oak_boat', ''), ('chest_boat', ''),
('minecart', ''), ('chest_minecart', 'Items:[{Slot:0b,id:"minecraft:apple",count:2}]'),
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""Manage parallel parity work: one worktree and branch per area, one integration branch.
python3 tools/supervise.py status # every worktree: branch, progress, last gate
python3 tools/supervise.py new dispensers # worktree ../dispensers on parity/dispensers, from the integration branch
python3 tools/supervise.py save [AREA ...] # commit and push unfinished work (before stopping agents)
python3 tools/supervise.py integrate parity/dispensers # merge into the integration branch if the gate passes
python3 tools/supervise.py integrate parity/a parity/b # several branches, one gate
The integration branch (`parity-base` by default) is checked out in its own
worktree; `integrate` merges there, runs tools/gate.py and pushes the
integration branch only when the gate passes, allowing only the harnesses
that already fail on the integration branch to keep failing. Otherwise it undoes the merge
and leaves the branch for its owner to fix. Worktrees live next to the
integration worktree and share its vanilla data: their `.local/` entries
link to `shared-local/` in the same directory.
"""
import argparse
import json
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
def git(*args, cwd=ROOT, check=True):
result = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True)
if check and result.returncode:
raise SystemExit(f"git {' '.join(args)} failed in {cwd}:\n{result.stderr.strip()}")
return result.stdout.strip()
def worktrees():
found, current = [], {}
for line in git("worktree", "list", "--porcelain").splitlines() + [""]:
if not line:
if current:
found.append(current)
current = {}
elif line.startswith("worktree "):
current["path"] = Path(line[len("worktree "):])
elif line.startswith("branch "):
current["branch"] = line[len("branch refs/heads/"):]
return found
def integration(base):
for tree in worktrees():
if tree.get("branch") == base:
return tree["path"]
raise SystemExit(f"No worktree has {base} checked out; create one with: git worktree add <path> {base}")
def count(range_, cwd):
return int(git("rev-list", "--count", range_, cwd=cwd, check=False) or 0)
def status(args):
base_tree = integration(args.base)
print(f"{'worktree':<16} {'branch':<26} {'ahead':>5} {'behind':>6} {'dirty':>5} {'unpushed':>8} gate")
for tree in worktrees():
path, branch = tree["path"], tree.get("branch", "(detached)")
if path.parent != base_tree.parent and path != base_tree:
continue
dirty = len(git("status", "--porcelain", cwd=path).splitlines())
remote = f"origin/{args.push_to if branch == args.base else branch}"
unpushed = count(f"{remote}..HEAD", path) if git("rev-parse", "--verify", "--quiet", remote, cwd=path, check=False) else "new"
gate = path / ".local" / "gate.json"
verdict = "never run"
if gate.exists():
result = json.loads(gate.read_text())
verdict = ("passed" if result["passed"] else "failed") + ("" if result["parity"] else " (no harnesses)")
if result["commit"] != git("rev-parse", "HEAD", cwd=path) or result["dirty"]:
verdict += ", older commit"
print(f"{path.name:<16} {branch:<26} {count(f'{args.base}..HEAD', path):>5} {count(f'HEAD..{args.base}', path):>6}"
f" {dirty:>5} {unpushed:>8} {verdict}")
def new(args):
base_tree = integration(args.base)
path = base_tree.parent / args.area
branch = f"parity/{args.area}"
if path.exists():
raise SystemExit(f"{path} already exists")
git("worktree", "add", "-b", branch, str(path), args.base)
shared = base_tree.parent / "shared-local"
(path / ".local").mkdir()
# Link the vanilla data, not the shared runner and datafix state beside it.
for entry in sorted(shared.iterdir()) if shared.is_dir() else []:
if entry.is_dir() and entry.name not in {"parity-shared", "datafix"}:
(path / ".local" / entry.name).symlink_to(entry)
print(f"{path} on {branch}, from {args.base} at {git('rev-parse', '--short', 'HEAD', cwd=path)}")
def save(args):
base_tree = integration(args.base)
for tree in worktrees():
path, branch = tree["path"], tree.get("branch")
if not branch or not branch.startswith("parity/") or path.parent != base_tree.parent:
continue
if args.areas and path.name not in args.areas:
continue
if git("status", "--porcelain", cwd=path):
git("add", "-A", cwd=path)
git("commit", "-q", "-m", f"WIP: unfinished {path.name} parity work\n\nWork in progress saved when its agent "
"stopped; may not build or pass its harnesses yet.\n\n"
"Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>", cwd=path)
print(f"{path.name}: committed unfinished work")
git("push", "-q", "origin", f"HEAD:{branch}", cwd=path)
print(f"{path.name}: {branch} pushed at {git('rev-parse', '--short', 'HEAD', cwd=path)}")
def integrate(args):
base_tree = integration(args.base)
if git("status", "--porcelain", "--untracked-files=no", cwd=base_tree):
raise SystemExit(f"{base_tree} has uncommitted changes; commit or stash them first")
before = git("rev-parse", "HEAD", cwd=base_tree)
state = base_tree / ".local/parity-runner/state.json"
known = sorted(name for name, record in json.loads(state.read_text())["harnesses"].items()
if record["status"] != "pass") if state.exists() else []
for branch in args.branches:
merge = subprocess.run(["git", "merge", "--no-ff", "--no-edit", branch], cwd=base_tree, capture_output=True, text=True)
if merge.returncode:
conflicts = git("diff", "--name-only", "--diff-filter=U", cwd=base_tree, check=False)
git("merge", "--abort", cwd=base_tree, check=False)
git("reset", "--hard", before, cwd=base_tree)
print(f"{branch} does not merge cleanly into {args.base}. Conflicts:\n{conflicts or merge.stdout + merge.stderr}")
print(f"Merge {args.base} into {branch}, resolve them there, and integrate again. Nothing was integrated.")
return 2
names = ", ".join(args.branches)
if git("rev-parse", "HEAD", cwd=base_tree) == before:
print(f"{names}: nothing new for {args.base}.")
return 0
gate = [sys.executable, "tools/gate.py", "-j", str(args.jobs), "--known-failures", ",".join(known)]
gate += ["--no-parity"] if args.no_parity else []
if subprocess.run(gate, cwd=base_tree).returncode:
git("reset", "--hard", before, cwd=base_tree)
print(f"The gate failed, so {names} were not integrated; {args.base} is back at {before[:9]}.")
return 1
git("push", "-q", "origin", f"{args.base}:{args.push_to}", cwd=base_tree)
print(f"Integrated {names}; {args.base} pushed to origin/{args.push_to} at {git('rev-parse', '--short', 'HEAD', cwd=base_tree)}.")
return 0
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--base", default="parity-base", help="the integration branch")
parser.add_argument("--push-to", default="t3/achieve-full-parity", help="remote branch the integration branch is pushed to")
commands = parser.add_subparsers(dest="command", required=True)
commands.add_parser("status").set_defaults(run=status)
command = commands.add_parser("new")
command.add_argument("area")
command.set_defaults(run=new)
command = commands.add_parser("save")
command.add_argument("areas", nargs="*")
command.set_defaults(run=save)
command = commands.add_parser("integrate")
command.add_argument("branches", nargs="+", help="merged in order, then gated together")
command.add_argument("-j", "--jobs", type=int, default=8)
command.add_argument("--no-parity", action="store_true", help="skip the vanilla harnesses in the gate")
command.set_defaults(run=integrate)
args = parser.parse_args()
return args.run(args) or 0
if __name__ == "__main__":
sys.exit(main())
+194
View File
@@ -0,0 +1,194 @@
#!/usr/bin/env python3
"""Compare the local player's ambient sounds with the vanilla 26.3 client.
The oracle runs the real `LocalPlayer.updateIsUnderwater` (enter/exit sounds
seeded from the level random, the `UnderLiquidAmbientSoundInstance`),
`UnderwaterAmbientSoundHandler`, `BubbleColumnAmbientSoundHandler` and
`BiomeAmbientSoundsHandler` over the real
`SoundEngine` (see VanillaSoundRig), then `SoundManager.tick`, once per client
tick. The `AMBIENT_SOUNDS` value (loops, moods and additions from the biomes
and dimensions of the data pack plus faster custom moods), the player's
position, eye height, eyes in water, spectator and removed flags and the
level's brightness are script inputs. Every step prints the level random's
next long (so every draw is compared), moodiness, the underwater state and
delay, the handler's loop instances (fade, direction, stopped, active), each
playing instance and the subtitle notifications. Horizon's `Ambience` and
`SoundEngine` replay the scripts.
"""
import json
import random
import struct
try:
from . import audio_harness as h
except ImportError:
import audio_harness as h
def dbits(v):
return struct.pack('>d', v).hex()
def settings():
"""Every AMBIENT_SOUNDS value in the data pack."""
data = h.RESOURCES / 'data/minecraft'
values = []
for path in sorted(list((data / 'worldgen/biome').glob('*.json')) + list((data / 'dimension_type').glob('*.json'))):
v = json.loads(path.read_text()).get('attributes', {}).get('minecraft:audio/ambient_sounds')
if v is None:
continue
additions = v.get('additions', [])
if isinstance(additions, dict):
additions = [additions]
mood = v.get('mood')
values.append(dict(loop=v.get('loop'), mood=None if mood is None else (mood['sound'], mood['tick_delay'], mood['block_search_extent'], mood['offset']),
additions=[(a['sound'], a['tick_chance']) for a in additions]))
return values
class Script:
def __init__(self):
self.lines = []
def add(self, *parts):
self.lines.append(' '.join(map(str, parts)))
def sounds(self, value):
mood = '-' if value['mood'] is None else '{},{},{},{}'.format(value['mood'][0], value['mood'][1], value['mood'][2], dbits(value['mood'][3]))
self.add('sounds', value['loop'] or '-', mood, *[f'{s},{dbits(c)}' for s, c in value['additions']])
def player(self, at=(0.5, 64.0, 0.5), eye=1.62, water=0, spectator=0, removed=0, mode=0, height=1.8, columns=()):
self.add('player', *map(dbits, at), h.bits(eye), water, spectator, removed, mode, h.bits(height),
*[f'{x},{y},{z},{d}' for x, y, z, d in columns])
def tick(self, n=1):
for _ in range(n):
self.add('tick')
def scripted(s, values):
by_loop = [v for v in values if v['loop']]
cave = next(v for v in values if v['mood'] and v['mood'][0] == 'minecraft:ambient.cave' and not v['loop'])
s.add('start', 1)
s.sounds(cave)
s.player(mode=1)
s.tick(6100)
s.player((100.25, -20.0, -7.75), mode=2)
s.tick(400)
s.player((3.5, 12.0, 3.5), mode=3)
s.tick(400)
# Biome loops cross-fading, back and forth.
s.add('start', 2)
for v in by_loop:
s.sounds(v)
s.tick(30)
s.sounds(by_loop[0])
s.tick(20)
s.sounds(by_loop[1])
s.tick(5)
s.sounds(by_loop[0])
s.tick(60)
s.sounds(dict(loop=None, mood=None, additions=[]))
s.tick(60)
# Water: enter, the loop's fade, sub-sounds, exit, re-entering mid-fade, spectators.
s.add('start', 3)
s.sounds(cave)
s.player(water=1, mode=0)
s.tick(300)
s.player(water=0)
s.tick(10)
s.player(water=1)
s.tick(3)
s.player(water=0)
s.tick(2)
s.player(water=1)
s.tick(60)
s.player(water=1, spectator=1)
s.tick(5)
s.player(water=0, spectator=1)
s.tick(5)
s.player(water=1, removed=1)
s.tick(5)
s.player(water=0)
s.tick(25)
# Silent ambient category: loops never start and linger.
s.add('start', 4)
s.add('volume', 8, h.bits(0.0))
s.sounds(by_loop[0])
s.tick(50)
s.add('volume', 8, h.bits(1.0))
s.sounds(by_loop[1])
s.tick(50)
s.sounds(by_loop[0])
s.tick(50)
# Bubble columns: entering, staying, the first tick, spectators, small boxes.
s.add('start', 5)
column = [(0, 64, 0, 1), (0, 65, 0, 1)]
s.player((0.5, 64.0, 0.5), water=1, columns=column)
s.tick(3)
s.player((3.5, 64.0, 0.5), water=1, columns=column)
s.tick(2)
s.player((0.5, 64.0, 0.5), water=1, columns=column)
s.tick(2)
s.player((0.5, 64.0, 0.5), water=1, columns=[(0, 64, 0, 0), (1, 64, 0, 1)])
s.tick(2)
s.player((3.5, 64.0, 0.5))
s.tick(2)
s.player((0.9, 64.5, 0.5), water=1, height=0.6, columns=[(1, 64, 0, 0), (0, 64, 0, 1)])
s.tick(2)
s.player((3.5, 64.0, 0.5))
s.tick(1)
s.player((0.5, 63.7, 0.5), spectator=1, columns=column)
s.tick(2)
def fuzz(s, rng, values, steps):
s.add('start', rng.getrandbits(63))
for _ in range(steps):
op = rng.random()
if op < 0.05:
v = rng.choice(values + [dict(loop=None, mood=None, additions=[])])
if rng.random() < 0.5 and v['mood']:
v = dict(v, mood=(v['mood'][0], rng.choice([20, 60, 150]), rng.choice([1, 4, 8, 16]), rng.choice([0.0, 2.0, 5.5])))
s.sounds(v)
elif op < 0.12:
at = (rng.uniform(-3e4, 3e4) if rng.random() < 0.2 else rng.uniform(-200, 200), rng.uniform(-64, 320), rng.uniform(-200, 200))
columns = []
if rng.random() < 0.3:
bx, by, bz = int(at[0] // 1), int(at[1] // 1), int(at[2] // 1)
columns = [(bx + rng.randrange(-1, 2), by + rng.randrange(-1, 3), bz + rng.randrange(-1, 2), rng.randrange(2)) for _ in range(rng.randrange(1, 4))]
s.player(at, rng.choice([1.62, 1.27, 0.4, 0.2]), int(rng.random() < 0.4), int(rng.random() < 0.05), int(rng.random() < 0.03), rng.randrange(4),
rng.choice([1.8, 1.5, 0.6]), columns)
elif op < 0.13:
s.add('volume', rng.choice([0, 8]), h.bits(rng.choice([0.0, 1.0, 0.5])))
else:
s.tick(rng.randrange(1, 40))
def fixtures():
values = settings()
s = Script()
scripted(s, values)
rng = random.Random(0x414d4249)
for _ in range(40):
fuzz(s, rng, values, 150)
return s.lines
def main():
lines = fixtures()
matched, report = h.run_harness(
'ambient', 'VanillaAmbientOracle', 'ambient_fixture', ''.join(l + '\n' for l in lines),
extra_sources=[h.lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java',
h.lab.ROOT / 'crates/horizon-client/src/ambience.rs',
h.lab.ROOT / 'crates/horizon-client/examples/audio_common/mod.rs'],
java_args=[h.RESOURCES], rust_args=[h.RESOURCES],
scope='Real LocalPlayer.updateIsUnderwater, UnderwaterAmbientSoundHandler and BiomeAmbientSoundsHandler (loop cross-fades, additions, '
'cave mood sampling, moodiness and the mood sound position) with UnderLiquidAmbientSoundInstance/UnderLiquidSubSound/LoopSoundInstance '
'ticking in the real SoundEngine: every level random draw, handler state, playing instance and notification per tick. The '
'AMBIENT_SOUNDS value, eyes-in-water state and brightness are inputs. BubbleColumnAmbientSoundHandler runs on a scripted block world.')
print(f'{matched:,} ambient lines match the pinned client ({len(lines):,} steps): {report}', flush=True)
if __name__ == '__main__':
main()
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
"""Compare the audio environment attributes with the vanilla 26.3 data pack.
The oracle evaluates vanilla's `EnvironmentAttributeSystem` (dimension layer,
biome positional layer, dimension timelines, weather layers) for every
dimension type and biome and prints `BACKGROUND_MUSIC` (all three tracks and
`BackgroundMusic.select` for each creative/underwater combination),
`MUSIC_VOLUME` and `AMBIENT_SOUNDS` (loop, mood, additions), plus the
`Musics` constants. Horizon's `MusicTables` and `AmbientTables` answer the same.
"""
try:
from . import audio_harness as h
except ImportError:
import audio_harness as h
def fixtures():
data = h.RESOURCES / 'data/minecraft'
biomes = sorted('minecraft:' + p.stem for p in (data / 'worldgen/biome').glob('*.json'))
dimensions = sorted('minecraft:' + p.stem for p in (data / 'dimension_type').glob('*.json'))
return [f'{d} {b} {t}' for d in dimensions for b in biomes for t in (0, 13000)]
def main():
lines = fixtures()
matched, report = h.run_harness(
'audio-attributes', 'VanillaAudioAttributesOracle', 'audio_attributes_fixture', ''.join(l + '\n' for l in lines),
extra_sources=[h.lab.ROOT / 'crates/horizon-client/src/music.rs', h.lab.ROOT / 'crates/horizon-client/src/ambience.rs'],
rust_args=[h.RESOURCES],
scope='Vanilla EnvironmentAttributeSystem values of audio/background_music (with BackgroundMusic.select), audio/music_volume and '
'audio/ambient_sounds for every dimension type x biome at two times of day, and the Musics constants.')
print(f'{matched:,} audio attribute lines match the pinned data ({len(lines):,} cases): {report}', flush=True)
if __name__ == '__main__':
main()
+162
View File
@@ -0,0 +1,162 @@
#!/usr/bin/env python3
"""Compare auto-jump with the pinned client: the real LocalPlayer.updateAutoJump
(and canAutoJump) on a player standing in an independently built copy of the
client's resident test scene, against MotionWorld::update_auto_jump over the
client's actual resources, collision registry and block-collision scan, for
steps, slabs, stairs, fences, walls, snow, carpets, honey, low ceilings and
overhangs approached from every angle with varied speeds, input vectors,
sizes, jump boost and the canAutoJump preconditions."""
import json
import math
import os
from pathlib import Path
import platform
import random
import struct
import subprocess
try:
from . import lab, oracle_harness as harness, test_rust_parity as base, test_model_baking_parity as baking, \
test_native_client as client
except ImportError:
import lab, oracle_harness as harness, test_rust_parity as base, test_model_baking_parity as baking
import test_native_client as client
def fbits(v):
return struct.pack('>f', v).hex()
def dbits(v):
return struct.pack('>d', v).hex()
BLOCKS = [
('stone', {}), ('stone', {}), ('stone', {}),
('stone_slab', {'type': 'bottom'}), ('stone_slab', {'type': 'top'}), ('stone_slab', {'type': 'double'}),
('oak_stairs', {'facing': 'north', 'half': 'bottom'}), ('oak_stairs', {'facing': 'east', 'half': 'bottom'}),
('oak_stairs', {'facing': 'south', 'half': 'top'}), ('oak_stairs', {'facing': 'west', 'half': 'bottom', 'shape': 'outer_left'}),
('oak_fence', {}), ('oak_fence', {'north': 'true', 'south': 'true'}), ('oak_fence_gate', {}),
('cobblestone_wall', {}), ('cobblestone_wall', {'up': 'true', 'east': 'tall'}),
('snow', {'layers': '1'}), ('snow', {'layers': '4'}), ('snow', {'layers': '8'}),
('white_carpet', {}), ('honey_block', {}), ('soul_sand', {}), ('farmland', {}), ('dirt_path', {}),
('chest', {}), ('enchanting_table', {}), ('oak_trapdoor', {}), ('oak_trapdoor', {'half': 'top'}),
('oak_trapdoor', {'open': 'true', 'facing': 'east'}), ('daylight_detector', {}), ('glass', {}), ('iron_bars', {}),
('lantern', {}), ('cake', {}), ('anvil', {}), ('hopper', {}), ('oak_leaves', {}), ('cobweb', {}), ('ladder', {}),
('red_bed', {'part': 'foot'}),
]
ORIGIN = (20, 4, -4)
def placed(rng, count):
blocks = {}
ox, oy, oz = ORIGIN
for _ in range(count):
x, y, z = ox + rng.randint(-3, 3), oy + rng.choice([0, 0, 0, 1, 1, 2, 3]), oz + rng.randint(-3, 3)
name, props = rng.choice(BLOCKS)
blocks[(x, y, z)] = [x, y, z, 'minecraft:' + name, props]
return list(blocks.values())
DIMS = [(0.6, 1.8), (0.6, 1.8), (0.6, 1.5), (0.6, 0.6), (0.3, 0.9), (1.2, 3.6), (0.6000000238418579, 1.7999999523162842)]
def player(rng, x, y, z, yaw):
w, h = rng.choice(DIMS)
return dict(pos=[dbits(x), dbits(y), dbits(z)], ground=rng.random() < 0.9, shift=rng.random() < 0.08,
yr=fbits(yaw), xr=fbits(rng.choice([0.0, 30.0, -45.0, 90.0, rng.uniform(-90, 90)])),
speed=fbits(rng.choice([0.1, 0.13000001, 0.03, 0.0, 0.2, rng.uniform(0, 0.3)])),
move=[fbits(v) for v in rng.choice([(0.0, 1.0), (0.0, 1.0), (1.0, 0.0), (-1.0, 0.0), (0.70710677, 0.70710677),
(0.0, -1.0), (0.0, 0.0), (0.3, 0.3)])],
width=fbits(w), height=fbits(h), boost=rng.choice([None] * 6 + [0, 1, 4, 255]),
enabled=rng.random() < 0.93, time=rng.choice([0] * 12 + [1, -3, 2]))
def cases(rng):
ox, oy, oz = ORIGIN
# Walk straight at each block from the four sides, at several speeds.
for name, props in BLOCKS:
for yaw, (dx, dz) in [(0.0, (0, 1)), (90.0, (-1, 0)), (180.0, (0, -1)), (-90.0, (1, 0)), (45.0, (-0.7, 0.7))]:
for step in (0.1, 0.215, 0.03, 0.0):
for lift in (0, 1):
blocks = [[ox, oy + lift, oz, 'minecraft:' + name, props]]
if lift:
blocks.append([ox, oy, oz, 'minecraft:stone', {}])
x = ox + 0.5 - dx * 1.1
z = oz + 0.5 - dz * 1.1
p = player(rng, x, float(oy), z, yaw)
p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[fbits(0.0), fbits(1.0)],
width=fbits(0.6), height=fbits(1.8), xr=fbits(0.0))
yield dict(blocks=blocks, player=p, xa=fbits(dx * step), za=fbits(dz * step))
# Ceilings above the player and above the step.
for ceiling in range(2, 6):
for step_height in (0, 1):
blocks = [[ox, oy + step_height, oz, 'minecraft:stone', {}], [ox - 1, oy + ceiling, oz, 'minecraft:stone', {}],
[ox, oy + ceiling + step_height, oz, 'minecraft:stone_slab', {'type': 'top'}]]
p = player(rng, ox - 0.5, float(oy), oz + 0.5, -90.0)
p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[fbits(0.0), fbits(1.0)],
width=fbits(0.6), height=fbits(1.8))
yield dict(blocks=blocks, player=p, xa=fbits(0.2), za=fbits(0.0))
for _ in range(9000):
blocks = placed(rng, rng.choice([1, 2, 4, 8, 16, 30]))
x = ox + rng.uniform(-2, 3)
z = oz + rng.uniform(-2, 3)
y = float(oy) + rng.choice([0.0, 0.0, 0.0, 0.5, 1.0, 0.0625, 0.9375])
yaw = rng.choice([0.0, 90.0, 180.0, -90.0, 45.0, rng.uniform(-360, 360)])
p = player(rng, x, y, z, yaw)
move = rng.choice([0.0, 0.0, 0.01, 0.1, 0.215, 0.3, rng.uniform(0, 0.4)])
angle = rng.uniform(0, 6.283)
yield dict(blocks=blocks, player=p, xa=fbits(math.cos(angle) * move), za=fbits(math.sin(angle) * move))
def main():
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
build = lab.LOCAL / 'rust-auto-jump-parity'
build.mkdir(exist_ok=True)
report = build / 'report.json'
report.unlink(missing_ok=True)
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
resources_before = client.resource_fingerprint(resources)
oracle = 'VanillaAutoJumpOracle'
parity = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
sources = [Path(__file__).resolve(), lab.ROOT / 'tools/oracle_harness.py', lab.ROOT / 'tools/lab.py',
parity / (oracle + '.java'), parity / 'VanillaSceneCollisionOracle.java',
parity / 'VanillaRegistryCollisionScanOracle.java', lab.ROOT / 'Cargo.lock',
lab.ROOT / 'crates/horizon-client/examples/auto_jump_probe.rs',
lab.ROOT / 'crates/horizon-client/src/auto_jump.rs', lab.ROOT / 'crates/horizon-client/src/motion.rs']
tested = base.source_hashes(sources)
fixtures = list(cases(random.Random(0x4155544f)))
inputs = build / 'cases.jsonl'
inputs.write_text(''.join(json.dumps(f, separators=(',', ':')) + '\n' for f in fixtures))
input_hash = lab.digest(inputs, 'sha256')
classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, libraries, lock['minecraft']['java_major'])
binary = harness.build_probe(build, 'auto_jump_probe')
harness.run_logged([binary, resources, inputs, build / 'rust.txt', build / 'scene.json'], build, 'rust', timeout=3600)
harness.java_run(build, classes, dependencies, oracle, [inputs, build / 'client.txt', resources, build / 'scene.json'], 'client')
matched = harness.compare(build / 'client.txt', build / 'rust.txt', 2 * len(fixtures))
base.ensure_sources_unchanged(sources, tested)
if input_hash != lab.digest(inputs, 'sha256') or resources_before != client.resource_fingerprint(resources):
raise AssertionError('Fixtures or resources changed during validation')
jumps = sum(1 for line in (build / 'rust.txt').read_text().splitlines() if line == 'jump 1')
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], fixtures=len(fixtures),
auto_jumps=jumps, sources_sha256=tested, input_sha256=input_hash, resources=resources_before,
client_jar_sha256=lab.digest(jars['client'], 'sha256'), matched_output_lines=matched,
output_sha256=lab.digest(build / 'rust.txt', 'sha256'),
scope='The actual LocalPlayer.updateAutoJump with canAutoJump (option, autoJumpTime, onGround, '
'isStayingOnGroundSurface, passenger, input move vector, getBlockJumpFactor over the real level) on a '
'LocalPlayer shell in an independently constructed copy of the resident test scene with each case\'s '
'real block states placed; collisions through CollisionGetter.getCollisions/BlockCollisions with the '
'player\'s EntityCollisionContext and real collision shapes, jump boost from a real MobEffectInstance. '
'Rust runs MotionWorld::update_auto_jump over the client\'s loaded resources, collision registry and '
'block-collision scan. Entity collisions (none in the scene) and the riding/minecart paths are not exercised.'))
print(f'{len(fixtures):,} auto-jump cases ({jumps:,} jumps) match the pinned client: {report}', flush=True)
if __name__ == '__main__':
main()
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""Compare the camera with the pinned client: Camera.tick (eye height and
field-of-view easing), alignWithEntity (view rotation quaternion and basis,
interpolated eye, third person back and front, camera distance and scale
attributes with mounts, getMaxZoom clipping against visual shapes, sleeping),
calculateFov/calculateHudFov (option, modifier, death and fluid effects,
panoramic mode), AbstractClientPlayer.getFieldOfViewModifier (flight, speed
attribute against walking speed, bow draw, spyglass), the walk and bob
history (ClientAvatarState, updateBob) and GameRenderer.bobHurt/bobView,
driven tick by tick and frame by frame with identical scripted states."""
import json
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 f32(v):
return struct.unpack('>f', struct.pack('>f', v))[0]
WALK = [0.1, 0.0, 0.05, 0.2, 1e-3, -0.1, 0.15]
SPEED = [f32(0.1), f32(0.1) * 1.3, 0.0, 0.03, 0.5, 1024.0, 0.13, f32(0.1) * 0.85, f32(0.1) * 1.4]
TICKS = [0, 1, 5, 10, 19, 20, 21, 72000, -5, 3]
def fov_fields(rng):
use = rng.choice([None, None, ['bow', rng.choice(TICKS)], ['spyglass', rng.choice(TICKS)], ['other', rng.choice(TICKS)]])
return dict(flying=rng.random() < 0.3, ws=fbits(rng.choice(WALK + [rng.uniform(-0.3, 0.3)])),
speed=dbits(rng.choice(SPEED + [rng.uniform(0, 2)])), use=use)
def fov_cases(rng):
for flying in (False, True):
for ws in WALK:
for speed in SPEED:
for use in [None, ['bow', 0], ['bow', 7], ['bow', 20], ['bow', 40], ['spyglass', 2], ['other', 5]]:
for fp in (False, True):
for scale in (0.0, 0.5, 1.0):
yield dict(t='fov', flying=flying, ws=fbits(ws), speed=dbits(speed), use=use, fp=fp, scale=fbits(scale))
for _ in range(3000):
yield dict(t='fov', **fov_fields(rng), fp=rng.random() < 0.6, scale=fbits(rng.choice([0.0, 1.0, rng.random()])))
FULL = [[0, 0, 0, 1, 1, 1]]
SHAPES = [FULL, FULL, [[0, 0, 0, 1, 0.5, 1]], [[0, 0.5, 0, 1, 1, 1]], [[0, 0, 0, 1, 1, 0.125]], [[0.375, 0, 0.375, 0.625, 1, 0.625]],
[[0, 0, 0, 0.5, 1, 1], [0.5, 0, 0.5, 1, 1, 1]], []]
def world(rng, center):
cells = {}
cx, cy, cz = center
for _ in range(rng.choice([0, 3, 10, 40, 120])):
p = (cx + rng.randint(-6, 6), cy + rng.randint(-3, 5), cz + rng.randint(-6, 6))
cells[f'{p[0]} {p[1]} {p[2]}'] = [[dbits(v) for v in box] for box in rng.choice(SHAPES)]
return cells
ANGLES = [0.0, 90.0, -90.0, 180.0, -180.0, 45.0, 360.0, 720.5, -33.3, 1e-3, 89.9]
def angle(rng):
return rng.choice(ANGLES + [rng.uniform(-90, 90), rng.uniform(-400, 400)])
def entity_state(rng, center):
pos = [center[i] + rng.uniform(0, 1) for i in range(3)]
prev = [p - rng.choice([0, 0, 0.1, 0.3, 1.0, rng.uniform(-1, 1)]) for p in pos]
kind = 'player' if rng.random() < 0.85 else 'marker'
xr, yr = angle(rng), angle(rng)
s = dict(kind=kind, pos=[dbits(v) for v in pos], prev=[dbits(v) for v in prev], xr=fbits(xr), yr=fbits(yr),
xro=fbits(rng.choice([xr, xr - 5, angle(rng)])), yro=fbits(rng.choice([yr, yr + 10, angle(rng)])),
eye=fbits(rng.choice([1.62, 1.27, 0.4, 0.2, 0.81, 3.24, rng.uniform(0, 4)])))
s.update(fov_fields(rng))
s.update(scale_attr=dbits(rng.choice([1.0, 1.0, 0.5, 2.0, 0.0625, 16.0, rng.uniform(0.0625, 3)])),
dist=dbits(rng.choice([4.0, 4.0, 0.0, 1.0, 10.0, 32.0, rng.uniform(0, 32)])),
sleeping=rng.choice([None] * 6 + [[None], [0], [1], [2], [3]]),
dead=rng.choice([None] * 6 + [0, 1, 5, 19, 20, 25]),
mount=rng.choice([None] * 4 + [[dbits(rng.choice([1.0, 2.0, 0.5])), dbits(rng.choice([4.0, 8.0, 1.0]))]]))
return s
def camera_cases(rng):
for n in range(2500):
center = rng.choice([(0, 64, 0), (-10, -60, 7), (1000, 120, -3000), (0, 0, 0)])
ops = []
for _ in range(rng.randrange(1, 40)):
kind = rng.choice(['entity', 'tick', 'tick', 'tick', 'frame', 'frame', 'frame', 'type'])
if not ops:
kind = 'entity'
if kind == 'entity':
ops.append(['entity', entity_state(rng, center)])
elif kind == 'tick':
ops.append(['tick'])
elif kind == 'frame':
pt = rng.choice([0.0, 1.0, 0.5, 0.25, 0.999, rng.random()])
ops.append(['frame', fbits(pt), rng.choice([0, 0, 0, 1, 2, 3]), rng.random() < 0.05])
else:
ops.append(['type', rng.randrange(3)])
yield dict(t='camera', fov=rng.choice([70, 30, 110, 90, rng.randint(30, 110)]),
effect=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), type=rng.choice([0, 1, 1, 2]),
cells=world(rng, center), ops=ops)
# A walled-in third-person camera stepping through every distance bound.
for dist in [0.0, 0.5, 1.0, 2.0, 4.0, 8.0, 32.0]:
for wall in range(0, 6):
for yaw in [0.0, 90.0, 180.0, 270.0, 45.0]:
cells = {}
for dx in range(-6, 7):
for dy in range(62, 68):
cells[f'{dx} {dy} {-wall - 1}'] = [[dbits(v) for v in box] for box in FULL]
cells[f'{dx} {dy} {wall + 1}'] = [[dbits(v) for v in box] for box in FULL]
s = dict(kind='player', pos=[dbits(0.5), dbits(64.0), dbits(0.5)], prev=[dbits(0.5), dbits(64.0), dbits(0.5)],
xr=fbits(15.0), yr=fbits(yaw), xro=fbits(15.0), yro=fbits(yaw), eye=fbits(1.62), flying=False,
ws=fbits(0.1), speed=dbits(f32(0.1)), use=None, scale_attr=dbits(1.0), dist=dbits(dist),
sleeping=None, dead=None, mount=None)
ops = [['entity', s]] + [['tick']] * 6 + [['frame', fbits(pt), 0, False] for pt in (0.0, 0.5, 1.0)]
yield dict(t='camera', fov=70, effect=dbits(1.0), type=1 + (wall % 2), cells=cells, ops=ops)
def bob_cases(rng):
for n in range(6000):
living = None
if rng.random() < 0.8:
living = dict(hurt=fbits(rng.choice([-1.0, -0.5, 0.0, 10.0, 9.5, 5.25, 1.0, rng.uniform(-2, 11)])),
duration=rng.choice([10, 10, 0, 5, 20]), dir=fbits(rng.choice([0.0, 90.0, -45.0, 180.0, rng.uniform(-360, 360)])),
death=rng.choice([None, None, None, fbits(rng.choice([0.0, 0.5, 19.5, 20.0, 25.0, rng.uniform(0, 30)]))]))
player = None
if rng.random() < 0.8:
player = [fbits(rng.choice([0.0, -0.3, -1.7, -100.25, rng.uniform(-1000, 0)])),
fbits(rng.choice([0.0, 0.1, 0.05, 0.0999, rng.uniform(0, 0.1)]))]
yield dict(t='bob', living=living, player=player, tilt=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])),
view=rng.random() < 0.8)
def avatar_cases(rng):
for n in range(1500):
ops = []
for _ in range(rng.randrange(1, 60)):
kind = rng.choice(['tick', 'move', 'move', 'bob', 'bob', 'frame', 'frame', 'reset'])
if kind == 'tick':
ops.append(['tick'])
elif kind == 'move':
ops.append(['move', fbits(rng.choice([0.0, 0.2158, -0.1, rng.uniform(-1, 1)])), fbits(rng.choice([0.0, 0.2806, rng.uniform(-1, 1)]))])
elif kind == 'bob':
v = [rng.choice([0.0, 0.05, -0.2, rng.uniform(-0.5, 0.5)]), rng.uniform(-1, 1), rng.choice([0.0, 0.08, rng.uniform(-0.5, 0.5)])]
ops.append(['bob', rng.random() < 0.7, rng.random() < 0.1, rng.random() < 0.1, [dbits(x) for x in v]])
elif kind == 'frame':
ops.append(['frame', fbits(rng.choice([0.0, 1.0, 0.5, rng.random()]))])
else:
ops.append(['reset'])
yield dict(t='avatar', ops=ops)
def make_cases(build):
rng = random.Random(0x43414d45)
path = build / 'cases.jsonl'
cases = build / 'cases'
cases.mkdir(exist_ok=True)
count = 0
with path.open('w') as out:
for generator in (fov_cases, camera_cases, bob_cases, avatar_cases):
for case in generator(rng):
text = json.dumps(case, separators=(',', ':'))
out.write(text + '\n')
if count < 20000:
(cases / str(count)).write_text(text)
count += 1
return path, count
def main():
scope = ('Real Camera.tick, tickFov, alignWithEntity (setRotation quaternion and forwards/up/left basis, move, '
'interpolated eye with eye-height easing, first person, third person back and mirrored front, scale and '
'camera_distance attributes including a living mount, getMaxZoom over the actual Level.clip with '
'ClipContext.Block.VISUAL against controlled visual shapes, sleeping bed orientation), calculateFov and '
'calculateHudFov (option, eased modifier, death, water/lava with the effect scale, panoramic), '
'AbstractClientPlayer.getFieldOfViewModifier with real Abilities, attribute maps and item stacks, '
'ClientAvatarState walk/bob history with AbstractClientPlayer.updateBob, and GameRenderer.bobHurt/bobView '
'as the full JOML pose matrix with its property flags. The camera entity is a shell with controlled '
'queries; getFluidInCamera is supplied (the fog harnesses cover fluid detection) and the new-minecart '
'interpolation branch is not exercised.')
harness.differential(
'rust-camera-parity', 'VanillaCameraOracle', 'camera_probe', make_cases, scope,
sources=[lab.ROOT / 'crates/horizon-client/src/camera.rs'])
if __name__ == '__main__':
main()
+9 -5
View File
@@ -17,6 +17,7 @@ usage: test_chunk_generation_parity.py [--seeds N] [--per-structure K]
[--filter REGEX] [--dimension overworld|the_nether|the_end] [--keep]
"""
import argparse
from concurrent.futures import ThreadPoolExecutor
import json
import os
import random
@@ -321,10 +322,13 @@ def main():
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)
# Vanilla and Horizon generate the same chunks independently: run them side by side.
with ThreadPoolExecutor(2) as pool:
rust_run = pool.submit(run_rust, binary, rust_path, seed, dimension, rects)
if not (os.environ.get('REUSE_VANILLA') and vanilla_path.exists()):
oracle.run(vanilla_path, ['dump', seed, dimension, *rects])
t1 = time.time()
stderr = rust_run.result()
t2 = time.time()
vanilla, rust = parse(vanilla_path), parse(rust_path)
for line in stderr.splitlines()[:5]:
@@ -342,7 +346,7 @@ def main():
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'{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, both sides {t2 - t0:.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')
+185
View File
@@ -0,0 +1,185 @@
#!/usr/bin/env python3
"""Compare entity death drops (loot tables, equipment drops, experience) with vanilla.
Java (VanillaEntityDeathLootOracle) builds the real victim, killer and damage
source on a stand-in ServerLevel and runs LivingEntity.die's drop step; Rust
(entity_death_loot_fixture) runs horizon_client::mobs::drops on the same cases.
Every living entity type with a loot table is killed by a player with and
without looting, by nothing, on fire, with a smelting weapon, as a baby, with
luck and with worn equipment, plus each table's special conditions (sheep
colours, cube sizes, frog kills, skeleton and charged creeper kills, fireballs,
lightning, raid captains and vehicles). Loot draws come from the world's random
sequences; several victims are killed in turn per case.
"""
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
# Living entity types with an entity loot table that the corpus skips: players
# and stands are not mobs, the dragon dies over 200 ticks, and the giant and
# the copper golem are not Horizon mob types.
SKIPPED = {'player', 'mannequin', 'armor_stand', 'ender_dragon', 'giant', 'copper_golem'}
# Types Horizon keeps body armour for in the head slot: their corpus wears
# body items instead of helmets.
BODY = {'horse', 'donkey', 'mule', 'skeleton_horse', 'zombie_horse', 'camel', 'camel_husk', 'llama', 'trader_llama',
'happy_ghast', 'nautilus', 'zombie_nautilus', 'sulfur_cube'}
WEAPONS = ['minecraft:iron_sword', 'minecraft:diamond_sword;looting:1', 'minecraft:diamond_sword;looting:2',
'minecraft:netherite_sword;looting:3', 'minecraft:golden_sword;fire_aspect:2', 'minecraft:diamond_axe;looting:3;fire_aspect:1']
ARMOUR = {'head': 'minecraft:iron_helmet', 'chest': 'minecraft:chainmail_chestplate', 'legs': 'minecraft:golden_leggings',
'feet': 'minecraft:diamond_boots', 'mainhand': 'minecraft:iron_sword', 'offhand': 'minecraft:shield'}
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple',
'blue', 'brown', 'green', 'red', 'black']
def corpus(types):
rng = random.Random(0x4C4F4F54)
cases = []
def add(name, **kv):
kv.setdefault('seed', rng.randrange(-2**63, 2**63))
kv.setdefault('rand', rng.randrange(-2**47, 2**47))
cases.append(name + ''.join(f' {k}={v}' for k, v in kv.items()))
for t in types:
n = t.split(':')[1]
add(f'{n}-player', type=t, killer='player', weapon='minecraft:iron_sword', kills=4)
add(f'{n}-none', type=t, source='generic', kills=3)
add(f'{n}-mob', type=t, killer='minecraft:spider', kills=2)
for i, weapon in enumerate(WEAPONS[1:]):
add(f'{n}-weapon{i}', type=t, killer='player', weapon=weapon, kills=4)
add(f'{n}-fire', type=t, killer='player', fire=1, kills=3)
add(f'{n}-fire-nokill', type=t, fire=1, source='fire', kills=2)
add(f'{n}-baby', type=t, killer='player', baby=1, weapon='minecraft:iron_sword;looting:3', kills=3)
add(f'{n}-luck', type=t, killer='player', luck=rng.choice([1, 2, 5]), kills=3)
add(f'{n}-arrow', type=t, killer='player', source='arrow', weapon='minecraft:bow;looting:3', kills=2)
head = 'body' if n in BODY else 'head'
armour = dict(ARMOUR)
if n in BODY:
armour['body'] = armour.pop('head').replace('helmet', 'horse_armor')
add(f'{n}-gear', type=t, killer='player', weapon='minecraft:iron_sword;looting:3', kills=6, **armour)
add(f'{n}-gear-plain', type=t, killer='player', kills=6, mainhand='minecraft:stone_axe', chance_mainhand=0.5,
**{head: 'minecraft:leather_helmet', f'chance_{head}': 2.0})
add(f'{n}-gear-nokill', type=t, source='generic', kills=4, feet='minecraft:iron_boots', chance_feet=1.0,
**{head: 'minecraft:carved_pumpkin', f'chance_{head}': 2.0})
add(f'{n}-gear-mob', type=t, killer='minecraft:skeleton', source='arrow', kills=4, feet='minecraft:iron_boots', chance_feet=1.0,
weapon='minecraft:bow;looting:3')
for color in DYES:
add(f'sheep-{color}', type='minecraft:sheep', color=color, killer='player', kills=3)
add(f'sheep-{color}-sheared', type='minecraft:sheep', color=color, sheared=1, killer='player', kills=2)
for cube in ['minecraft:slime', 'minecraft:magma_cube', 'minecraft:sulfur_cube']:
for size in [1, 2, 3, 4]:
add(f'{cube[10:]}-size{size}', type=cube, size=size, killer='player', weapon='minecraft:iron_sword;looting:2', kills=4)
for frog in ['temperate', 'warm', 'cold']:
for size in [1, 2, 4]:
add(f'magma_cube-frog-{frog}-{size}', type='minecraft:magma_cube', size=size, killer='minecraft:frog', frog='minecraft:' + frog,
pkill=rng.choice([0, 1]), kills=3)
add('creeper-skeleton', type='minecraft:creeper', killer='minecraft:skeleton', source='arrow', pkill=1, kills=3)
add('creeper-stray', type='minecraft:creeper', killer='minecraft:stray', source='arrow', kills=2)
for victim in ['zombie', 'skeleton', 'creeper', 'wither_skeleton', 'piglin', 'zombie_villager', 'cow']:
add(f'charged-{victim}', type='minecraft:' + victim, killer='minecraft:creeper', charged=1, source='explosion', kills=2)
add(f'uncharged-{victim}', type='minecraft:' + victim, killer='minecraft:creeper', source='explosion', kills=2)
add('ghast-fireball', type='minecraft:ghast', killer='player', source='fireball', kills=4)
add('ghast-fireball-ghast', type='minecraft:ghast', killer='minecraft:ghast', source='fireball', kills=2)
add('turtle-lightning', type='minecraft:turtle', source='lightning', kills=3)
add('turtle-lightning-player', type='minecraft:turtle', source='lightning', pkill=1, kills=3)
add('pillager-captain', type='minecraft:pillager', captain=1, leader=1, killer='player', kills=3)
add('pillager-captain-none', type='minecraft:pillager', captain=1, leader=1, source='generic', kills=2)
add('pillager-captain-looting', type='minecraft:pillager', captain=1, leader=1, killer='player',
weapon='minecraft:iron_sword;looting:3', kills=4, chance_head=2.0)
add('pillager-banner-only', type='minecraft:pillager', captain=1, killer='player', kills=3)
add('pillager-leader-only', type='minecraft:pillager', leader=1, killer='player', kills=2)
add('vindicator-captain', type='minecraft:vindicator', captain=1, leader=1, killer='player', kills=2)
for animal in ['pig', 'strider', 'horse', 'camel', 'donkey']:
add(f'{animal}-saddle', type='minecraft:' + animal, saddle='minecraft:saddle', chance_saddle=2.0, killer='player', kills=2)
add(f'{animal}-saddle-default', type='minecraft:' + animal, saddle='minecraft:saddle', killer='player', kills=6)
add('zombie-horse', type='minecraft:zombie', vehicle='minecraft:zombie_horse', killer='player', kills=4)
add('zombie-baby-chicken', type='minecraft:zombie', baby=1, vehicle='minecraft:chicken', killer='player', kills=3)
add('zombie-baby-chicken-none', type='minecraft:zombie', baby=1, vehicle='minecraft:chicken', source='generic', kills=2)
add('husk-camel', type='minecraft:husk', vehicle='minecraft:camel_husk', killer='player', kills=3)
for weapon in WEAPONS:
add('wither-' + weapon.split(';')[-1].replace(':', ''), type='minecraft:wither', killer='player', weapon=weapon, kills=2)
return cases
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--prepare', action='store_true')
args = parser.parse_args()
build = lab.LOCAL / 'rust-entity-death-loot-parity'
build.mkdir(parents=True, exist_ok=True)
if args.prepare:
lab.prepare()
lock, jars, libraries = base.verify_artifacts()
resources = lab.LOCAL / 'horizon-client/26.3'
tables = resources / 'data/minecraft/loot_table/entities'
types = sorted('minecraft:' + p.stem for p in tables.glob('*.json') if p.stem not in SKIPPED)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityDeathLootOracle.java'
sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/entity_death_loot_fixture.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/drops.rs', lab.ROOT / 'crates/horizon-world/src/loot.rs']
tested = base.source_hashes(sources)
inputs = build / 'inputs.txt'
cases = corpus(types)
inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8')
classes = build / 'classes'
classes.mkdir(exist_ok=True)
deps = os.pathsep.join(map(str, libraries))
def run(command, name):
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'),
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaEntityDeathLootOracle', inputs, build / 'server.txt'], 'server')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'entity_death_loot_fixture'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/entity_death_loot_fixture'
run([binary, resources, inputs, build / 'rust.txt'], 'rust')
errors = [l for l in (build / 'server.txt').read_text().splitlines() if l.startswith('error ')]
if errors:
raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}')
try:
matched = base.compare(build / 'server.txt', build / 'rust.txt')
except AssertionError as error:
raise SystemExit(str(error) + explain(build)) from None
base.ensure_sources_unchanged(sources, tested)
lab.write_json(build / 'report.json', {
'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases),
'types': len(types), 'skipped': sorted(SKIPPED), 'matched_output_lines': matched, 'sources_sha256': tested,
'scope': 'LivingEntity.dropAllDeathLoot after the killer\'s killedEntity hook: entity loot tables under the world random '
'sequence, Mob.dropCustomDeathLoot equipment drops and durability, species death loot, experience orbs.'})
print(f'{len(cases):,} death-drop cases over {len(types)} entity types match vanilla ({matched:,} lines)')
def explain(build):
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 / 'server.txt'), sections(build / 'rust.txt')
bad = [n for n in left if left[n] != right.get(n)]
report = f'\n{len(bad)} differing cases'
for name in bad[:30]:
a, b = left[name], right.get(name, [])
diffs = [(x, y) for x, y in zip(a, b) if x != y][:3]
if len(a) != len(b):
diffs.append((f'<{len(a)} lines>', f'<{len(b)} lines>'))
report += f'\n {name}: {diffs}'
return report
if __name__ == '__main__':
main()
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Compare the frame limiter with the pinned client: the real
FramerateLimiter.limitDisplayFPS bytecode, its clock calls rewritten to a
scripted virtual clock, against the Rust limiter with the same script, frame
by frame: sleep requests, spin-waits, overshoot averaging and its reset on a
limit change, interrupted sleeps, oversleep and early wake-ups, the "below
260" condition of Minecraft.runTick, and the limits FramerateLimitTracker
hands it (option values, 60 in menus, 10 when minimised or idle)."""
import json
import random
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
LIMITS = [10, 30, 60, 60, 120, 144, 165, 240, 250, 259, 260, 1, 2, 7, 1000, 2**31 - 1]
def cases(rng):
for limit in LIMITS:
for overshoot in ([0], [50_000], [3_000_000], [30_000_000], [-200_000], [100_000, 2_500_000, 0, 24_999_999, 25_000_000]):
for spin in (1_000, 50_000, 7_919):
frames = [[rng.choice([0, 1_000_000, 4_000_000, 16_000_000]), limit] for _ in range(12)]
yield dict(now=10**12, call=rng.choice([0, 25]), spin=spin, overshoot=overshoot, interrupts=[False],
last=10**12, average=0, last_limit=0, frames=frames)
for n in range(5000):
frames = []
limit = rng.choice(LIMITS)
for _ in range(rng.randrange(1, 40)):
if rng.random() < 0.15:
limit = rng.choice(LIMITS)
work = rng.choice([0, 100_000, 2_000_000, 5_000_000, 16_666_666, 30_000_000, 120_000_000, rng.randrange(0, 50_000_000)])
frames.append([work, limit])
start = rng.choice([0, 10**9, 10**15, rng.randrange(0, 10**16)])
yield dict(now=start, call=rng.choice([1, 30, 400, 20_000]), spin=rng.choice([100, 1_000, 70_000, 600_000]),
overshoot=[rng.choice([0, 30_000, 80_000, 1_200_000, 2_100_000, 24_000_000, 26_000_000, -300_000, rng.randrange(-1_000_000, 4_000_000)])
for _ in range(rng.randrange(1, 8))],
interrupts=[False] + [rng.random() < 0.3 for _ in range(rng.randrange(0, 5))],
last=start - rng.choice([0, 1, 5_000_000, 200_000_000]),
average=rng.choice([0, 0, 1, 500_000, 2_000_000]), last_limit=rng.choice([0, 60, limit]), frames=frames)
def make_cases(build):
rng = random.Random(0x46505331)
path = build / 'cases.jsonl'
count = 0
with path.open('w') as out:
for case in cases(rng):
out.write(json.dumps(case, separators=(',', ':')) + '\n')
count += 1
return path, count
def main():
scope = ('The actual FramerateLimiter.limitDisplayFPS bytecode from the client jar, loaded through a ClassFile '
'rewrite that redirects System.nanoTime, LockSupport.parkNanos, Thread.interrupted and Thread.onSpinWait '
'to a scripted virtual clock (query cost, oversleep/early wake per park, spin cost, interrupt pattern), '
'with its static state seeded per case and the Minecraft.runTick "limit < 260" gate. Compares every '
'frame\'s park requests, spin count, clock queries, lastFrameTime, averageOvershootNs and '
'lastFramerateLimit. The limits themselves (FramerateLimitTracker) are compared by the game loop harness; '
'real OS sleep accuracy is outside the comparison.')
harness.differential(
'rust-frame-limiter-parity', 'VanillaFrameLimiterOracle', 'frame_limiter_probe', make_cases, scope,
sources=[lab.ROOT / 'crates/horizon-client/src/window.rs'])
if __name__ == '__main__':
main()
+256
View File
@@ -0,0 +1,256 @@
#!/usr/bin/env python3
"""Differential mob AI harness.
The Java oracle (VanillaMobAiOracle) runs vanilla mobs in a real, headless, flat vanilla server
level: each scenario builds a scene, places a target player and mobs with seeded random sources
and ticks the mobs the way ServerLevel.tick does. The Rust probe (mob_ai_probe) replays the same
scenarios on Horizon's mob AI. Both print every mob's AI-visible state after every tick (position,
motion, rotations, running goals and target goals, attack target, navigation path, move and look
controls, movement input, brain activities and memories) and the sounds played; this harness
reports, per scenario and mob, how many ticks match before the first divergence and what differs.
python3 tools/test_mob_ai_parity.py [--only NAME ...] [--rust-only] [--java-only] [--report-only]
"""
import argparse
import os
import struct
import subprocess
import sys
from pathlib import Path
try:
from . import lab, oracle_harness, test_rust_parity as base, test_model_baking_parity as baking
except ImportError:
import lab
import oracle_harness
import test_rust_parity as base
import test_model_baking_parity as baking
FLOOR = -60 # top of the flat preset's grass layer + 1
def ring(x0, z0, size, state, y=FLOOR):
return [f'fill {x0 - size} {y} {z0 - size} {x0 + size} {y} {z0 + size} {state}']
# Each scenario is (name, ticks, options, lines); positions are relative to the scenario origin
# and translated by the generator so scenarios never share chunks.
def scenarios():
s = []
def add(name, ticks, lines, opts=''):
s.append((name, ticks, opts, lines))
# Passive and hostile land mobs on open grass with a survival player nearby.
for species, seed in [('zombie', 1), ('skeleton', 2), ('creeper', 3), ('spider', 4), ('husk', 5),
('cow', 6), ('pig', 7), ('chicken', 8), ('sheep', 9), ('wandering_trader', 10),
('villager', 11), ('drowned', 12), ('enderman', 13), ('witch', 14)]:
add(f'{species}_player', 200, [
'player 6.5 -60 0.5',
f'mob minecraft:{species} 0.5 -60 0.5 0 {seed} persistent',
])
add(f'{species}_alone', 200, [
f'mob minecraft:{species} 0.5 -60 0.5 90 {seed * 7 + 1} persistent',
])
# Drowned in a pool with the player on the shore and in the water.
add('drowned_pool', 200, ['fill -6 -64 -6 6 -61 6 minecraft:water',
'player 9.5 -60 0.5',
'mob minecraft:drowned 0.5 -63 0.5 0 21 persistent'])
add('drowned_pool_swimmer', 200, ['fill -6 -64 -6 6 -61 6 minecraft:water',
'player 3.5 -62 0.5',
'mob minecraft:drowned -3.5 -63 0.5 0 22 persistent'])
# Night: undead do not burn, monsters seek darkness.
add('zombie_night', 200, ['player 10.5 -60 0.5', 'mob minecraft:zombie 0.5 -60 0.5 0 31 persistent'], 'time=18000')
add('skeleton_day_burn', 120, ['mob minecraft:skeleton 0.5 -60 0.5 0 32 persistent'])
# The wither (summoned, not built: no invulnerable spawn phase).
add('wither_player', 200, ['player 10.5 -60 0.5', 'mob minecraft:wither 0.5 -58 0.5 0 41 persistent'])
# A villager with a job site, a bed and a bell.
add('villager_village', 300, [
'block 4 -60 0 minecraft:composter',
'block -4 -60 2 minecraft:red_bed[facing=north,part=foot]',
'block -4 -60 1 minecraft:red_bed[facing=north,part=head]',
'block 0 -60 -6 minecraft:bell',
'player 12.5 -60 0.5',
'mob minecraft:villager 0.5 -60 0.5 0 51 persistent',
])
return s
def write_scenarios(path, chosen):
lines = []
for i, (name, ticks, opts, body) in chosen:
ox, oz = 512 * (i + 1), 0
lines.append(f'scenario {name} ticks={ticks} {opts}'.rstrip())
lines.append(f'origin {ox} {oz}')
for line in body:
f = line.split()
if f[0] == 'player':
f[1] = repr(float(f[1]) + ox)
f[3] = repr(float(f[3]) + oz)
elif f[0] == 'mob':
f[2] = repr(float(f[2]) + ox)
f[4] = repr(float(f[4]) + oz)
elif f[0] == 'block':
f[1] = str(int(f[1]) + ox)
f[3] = str(int(f[3]) + oz)
elif f[0] == 'fill':
for k in (1, 4):
f[k] = str(int(f[k]) + ox)
for k in (3, 6):
f[k] = str(int(f[k]) + oz)
lines.append(' '.join(f))
lines.append('end')
path.write_text('\n'.join(lines) + '\n')
def parse(path):
"""{scenario: {tick: {mob: {field: value}}, sounds: {tick: [..]}}}"""
result, cur = {}, None
for line in path.read_text().splitlines():
if line.startswith('== '):
cur = result.setdefault(line[3:], {'ticks': {}, 'sounds': {}})
continue
head, *fields = line.split('\t')
parts = head.split(' ', 2)
t = int(parts[0])
if parts[1] == 'sound':
cur['sounds'].setdefault(t, []).append(parts[2])
continue
if parts[1] == 'trace':
cur.setdefault('trace', {}).setdefault(t, []).append(parts[2])
continue
mob = int(parts[1])
row = {}
if len(parts) > 2:
row['removed'] = parts[2]
for f in fields:
k, _, v = f.partition(' ')
row[k] = v
cur['ticks'].setdefault(t, {})[mob] = row
return result
def decode(value):
"""Hex float/double fields made readable."""
def one(x):
try:
if len(x) > 8:
return f'{struct.unpack(">d", int(x, 16).to_bytes(8, "big"))[0]!r}'
return f'{struct.unpack(">f", int(x, 16).to_bytes(4, "big"))[0]:.9g}'
except ValueError:
return x
out = []
for word in value.split(' '):
out.append(','.join(one(p) if all(c in '0123456789abcdef' for c in p) and len(p) >= 5 else p for p in word.split(',')))
return ' '.join(out)
MULT, MASK = 0x5DEECE66D, (1 << 48) - 1
def draws(before, after, limit=20000):
"""How many LegacyRandomSource steps lead from one state to the next."""
try:
s, goal = int(before, 16), int(after, 16)
except (TypeError, ValueError):
return '?'
for n in range(limit):
if s == goal:
return n
s = (s * MULT + 11) & MASK
return f'>{limit}'
def compare(vanilla, rust, fields=None):
"""Returns (report lines, totals)."""
report, totals = [], {'mob_ticks': 0, 'matched': 0, 'scenarios': 0, 'clean': 0}
for name, v in vanilla.items():
r = rust.get(name)
totals['scenarios'] += 1
if r is None:
report.append(f'{name}: missing from Horizon')
continue
mobs = sorted({m for t in v['ticks'].values() for m in t})
clean = True
for mob in mobs:
ticks = sorted(v['ticks'])
first = None
for t in ticks:
a = v['ticks'][t].get(mob)
b = r['ticks'].get(t, {}).get(mob)
totals['mob_ticks'] += 1
if a == b or (b is not None and fields and all(a.get(k) == b.get(k) for k in fields)):
if first is None:
totals['matched'] += 1
continue
if first is None:
first = t
diffs = []
for k in (a or {}):
if b is None or a.get(k) != b.get(k):
show = (lambda x: x) if k == 'rng' else decode
diffs.append(f'{k}: vanilla {show(a.get(k, "?"))} | horizon {show((b or {}).get(k, "?"))}')
for k in (b or {}):
if a is None or k not in a:
diffs.append(f'{k}: vanilla ? | horizon {decode(b[k])}')
prev_v = v['ticks'].get(t - 1, {}).get(mob, {}).get('rng')
prev_r = r['ticks'].get(t - 1, {}).get(mob, {}).get('rng')
report.append(f'{name} mob {mob}: first divergence at tick {t} of {len(ticks)} '
f'(random draws this tick: vanilla {draws(prev_v, (a or {}).get("rng"))}, '
f'horizon {draws(prev_r, (b or {}).get("rng"))})')
for line in [x for x in v.get('trace', {}).get(t, []) if x.split(' ', 1)[0] == str(mob)][:40]:
report.append(' vanilla ' + line)
report.extend(' ' + d for d in diffs[:12])
if first is not None:
clean = False
# Sounds: first differing tick.
for t in sorted(set(v['sounds']) | set(r['sounds'])):
if v['sounds'].get(t, []) != r['sounds'].get(t, []):
report.append(f'{name}: sounds differ at tick {t}: vanilla {v["sounds"].get(t, [])} | horizon {r["sounds"].get(t, [])}')
clean = False
break
totals['clean'] += clean
if clean:
report.append(f'{name}: all {len(v["ticks"])} ticks match')
return report, totals
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--only', nargs='*')
parser.add_argument('--java-only', action='store_true')
parser.add_argument('--rust-only', action='store_true', help='reuse the last vanilla output')
parser.add_argument('--report-only', action='store_true', help='print divergences without failing')
args = parser.parse_args()
build = lab.LOCAL / 'mob-ai-parity'
build.mkdir(parents=True, exist_ok=True)
chosen = [(i, s) for i, s in enumerate(scenarios()) if not args.only or any(o in s[0] for o in args.only)]
inputs = build / 'scenarios.txt'
write_scenarios(inputs, chosen)
lock, jars, _ = base.verify_artifacts()
if not args.rust_only:
classes, dependencies, _ = oracle_harness.compile_oracle(build, 'VanillaMobAiOracle', jars, baking.client_libraries(),
lock['minecraft']['java_major'])
oracle_harness.run_logged(['java', '-Xmx3g', '-Djava.awt.headless=true', '-cp', str(classes) + os.pathsep + dependencies,
'dev.horizonlab.parity.VanillaMobAiOracle', inputs, build / 'vanilla.txt'],
build, 'vanilla', timeout=3600)
if not args.java_only:
oracle_harness.run_logged(['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--example', 'mob_ai_probe'],
build, 'compile-rust')
binary = lab.cargo_target() / 'release/examples/mob_ai_probe'
oracle_harness.run_logged([binary, lab.ROOT / '.local/horizon-client/26.3', inputs, build / 'horizon.txt'], build, 'horizon')
if args.java_only:
return
names = {s[0] for _, s in chosen}
vanilla = {k: v for k, v in parse(build / 'vanilla.txt').items() if k in names}
report, totals = compare(vanilla, parse(build / 'horizon.txt'))
(build / 'report.txt').write_text('\n'.join(report) + '\n')
print('\n'.join(report))
print(f"{totals['clean']}/{totals['scenarios']} scenarios match entirely; "
f"{totals['matched']}/{totals['mob_ticks']} mob-ticks match before each mob's first divergence")
if not args.report_only and totals['clean'] != totals['scenarios']:
raise SystemExit(1)
if __name__ == '__main__':
main()
+1 -1
View File
@@ -63,7 +63,7 @@ def main():
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx1G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]), 'dev.horizonlab.parity.VanillaMobAttributesOracle', build / 'vanilla.txt'], 'java')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'mob_attributes_fixture'], 'compile-rust')
binary = lab.ROOT / 'target/release/examples/mob_attributes_fixture'
binary = lab.cargo_target() / 'release/examples/mob_attributes_fixture'
resources = lab.ROOT / '.local/horizon-client/26.3'
run([binary, resources, build / 'rust.txt'], 'rust')
vanilla, rust = parse(build / 'vanilla.txt'), parse(build / 'rust.txt')
+167
View File
@@ -0,0 +1,167 @@
#!/usr/bin/env python3
"""Compare the music manager with the vanilla 26.3 client.
The oracle runs the real `MusicManager` over the real `SoundEngine` (OpenAL
Soft "No Output" device, see VanillaSoundRig). The situation
(`getSituationalMusic`, `getMusicVolume`), the loading screen, pauses, the
end of a track, `stopPlaying`, `setMinutesBetweenSongs`, the music category
volume and `showNowPlayingToastIfNeeded` are script inputs; every step prints
the current track, `nextSongDelay`, `currentGain`, `toastShown`, the toast
calls, the MUSIC category gain and the music channel's AL source. Horizon's
`MusicManager` and `SoundEngine` replay the scripts. Tracks use events whose
variants share one volume, since `forMusic` resolves with an unseeded random.
"""
import random
try:
from . import audio_harness as h
except ImportError:
import audio_harness as h
TRACKS = ['minecraft:music.credits', 'minecraft:music.dragon', 'minecraft:music.end', 'minecraft:music.under_water',
'minecraft:music.overworld.swamp', 'minecraft:music_disc.cat', 'minecraft:music_disc.13']
ODD = ['minecraft:music.nether.warped_forest', 'minecraft:not.a.track']
class Script:
def __init__(self):
self.lines = []
def add(self, *parts):
self.lines.append(' '.join(map(str, parts)))
def situation(self, sound=None, lo=0, hi=0, replace=0, volume=1.0):
self.add('situation', '-' if sound is None else f'{sound},{lo},{hi},{replace}', h.bits(volume))
def tick(self, n=1, loading=0, paused=0):
for _ in range(n):
self.add('tick', loading, paused)
def scripted(s):
end, dragon, water, credits, cat = TRACKS[2], TRACKS[1], TRACKS[3], TRACKS[0], TRACKS[5]
s.add('start', 1, 'DEFAULT')
# Menu-like music: 20..600 ticks, replacing.
s.situation(end, 20, 600, 1)
s.tick(3, loading=1)
s.tick(120)
s.add('finish')
s.tick(650)
# Game music does not replace, and the next delay comes from its range.
s.situation(water, 12000, 24000, 0)
s.tick(5)
s.add('finish')
s.tick(30)
s.add('freq', 'FREQUENT')
s.tick(3)
s.add('freq', 'CONSTANT')
s.tick(110)
s.add('freq', 'DEFAULT')
s.tick(2)
# A replacing track stops the current one over the following ticks.
s.situation(dragon, 0, 0, 1)
s.tick(30)
s.situation(credits, 0, 0, 1)
s.tick(30)
s.situation(None)
s.tick(5)
s.add('finish')
s.tick(5)
s.situation(end, 6000, 24000, 1)
s.tick(130)
# Music volume fades: down to silence, then up from a partial volume.
s.situation(end, 6000, 24000, 1, volume=0.0)
s.tick(320)
s.situation(cat, 0, 0, 1, volume=0.25)
s.tick(5)
s.situation(cat, 0, 0, 1, volume=1.0)
s.tick(400)
s.situation(cat, 0, 0, 1, volume=0.6)
s.tick(80)
# Silent starts and the toast, stops, pauses.
s.add('volume', 1, h.bits(0.0))
s.add('stop')
s.situation(dragon, 0, 0, 1)
s.tick(105)
s.add('toast')
s.add('volume', 1, h.bits(0.5))
s.add('toast')
s.tick(2)
s.add('stopmusic', f'{end},0,0,1')
s.add('stopmusic', f'{dragon},0,0,1')
s.tick(105, paused=1)
s.add('finish')
s.tick(3, paused=1)
s.tick(5)
s.add('stopall')
s.tick(5)
# Events that cannot play.
for event in ODD:
s.add('start', 7, 'DEFAULT')
s.situation(event, 0, 40, 1)
s.tick(150)
# Real Musics delays over a long session.
s.add('start', 99, 'DEFAULT')
s.situation(water, 12000, 24000, 0)
s.tick(130)
s.add('finish')
s.tick(24100)
def fuzz(s, rng, steps):
s.add('start', rng.getrandbits(63), rng.choice(['DEFAULT', 'FREQUENT', 'CONSTANT']))
for _ in range(steps):
op = rng.random()
if op < 0.08:
sound = rng.choice(TRACKS + ODD[:1]) if rng.random() < 0.9 else None
lo = rng.choice([0, 20, 100, 300])
s.situation(sound, lo, lo + rng.choice([0, 50, 280, 600]), int(rng.random() < 0.5),
rng.choice([1.0, 1.0, 1.0, 0.0, 0.5, rng.random()]))
elif op < 0.13:
s.add('finish')
elif op < 0.15:
s.add('stop')
elif op < 0.16:
s.add('stopmusic', f'{rng.choice(TRACKS)},0,0,1')
elif op < 0.17:
s.add('freq', rng.choice(['DEFAULT', 'FREQUENT', 'CONSTANT']))
elif op < 0.18:
s.add('toast')
elif op < 0.20:
s.add('volume', rng.choice([0, 1]), h.bits(rng.choice([0.0, 1.0, 0.5])))
elif op < 0.21:
s.add('stopall')
elif op < 0.25:
s.tick(rng.randrange(1, 30), loading=1)
elif op < 0.28:
s.tick(rng.randrange(1, 30), paused=1)
else:
s.tick(rng.randrange(1, 60))
def fixtures():
s = Script()
scripted(s)
rng = random.Random(0x4d55534943)
for _ in range(60):
fuzz(s, rng, 120)
return s.lines
def main():
lines = fixtures()
matched, report = h.run_harness(
'music', 'VanillaMusicOracle', 'music_fixture', ''.join(l + '\n' for l in lines),
extra_sources=[h.lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java',
h.lab.ROOT / 'crates/horizon-client/src/music.rs',
h.lab.ROOT / 'crates/horizon-client/examples/audio_common/mod.rs'],
java_args=[h.RESOURCES], rust_args=[h.RESOURCES],
scope='Real MusicManager.tick/startPlaying/stopPlaying/fadePlaying/setMinutesBetweenSongs/showNowPlayingToastIfNeeded with a seeded '
'random over the real SoundEngine: track starts and replacements, nextSongDelay draws, the three music frequencies, the loading '
'screen hold, fades and the MUSIC category gain, silent starts, toasts, pauses, track ends and unplayable events. The situation '
'(getSituationalMusic/getMusicVolume) is an input here; see test_audio_attributes_parity.py for the attribute values.')
print(f'{matched:,} music lines match the pinned client ({len(lines):,} steps): {report}', flush=True)
if __name__ == '__main__':
main()
+602
View File
@@ -0,0 +1,602 @@
#!/usr/bin/env python3
"""Compare natural spawning (NaturalSpawner) with vanilla.
Java (VanillaNaturalSpawnOracle) runs vanilla's NaturalSpawner on a stand-in
ServerLevel built from each case: boxes of blocks, light and biomes, structure
starts with their pieces, existing mobs, players, the world spawn point and
unloaded chunks. Rust (natural_spawn_fixture) runs
horizon_client::mobs::spawn_selection on the same world. Three modes:
- chunk: createState over the case's mobs (category counts, spawn potential
charges, local caps), getFilteredSpawningCategories under the global caps,
then spawnForChunk (local caps, getRandomPosWithin, spawnCategoryForPosition);
- pos: spawnCategoryForPosition from a chosen start (surfaces, caves, water,
lava, structures);
- gen: spawnMobsForChunkGeneration.
Each case's log lists every attempt (the nearest player lookup), each type that
passed isValidSpawnPostitionForType with the spawn potential's answer, each
spawn with its exact position and yaw bits, the heightmap columns of
chunk-generation attempts, and the next draw of the spawner's random, which
pins every draw in between. Worlds cover the overworld, nether and end, their
biomes, caves, water and lava, block and sky light, day, night and thunder,
peaceful to hard, spawn costs (soul sand valley, warped forest), structure
spawn overrides (fortress, swamp hut, monument, outpost, trial chambers,
ancient city), mob caps, players near and far, spectators and the world spawn.
"""
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
R = 48 # world boxes span [-R, 16 + R) around chunk (0, 0)
OVERWORLD = {
# biome: (top block, filler)
'minecraft:plains': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:forest': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:birch_forest': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:dark_forest': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:flower_forest': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:sunflower_plains': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:meadow': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:cherry_grove': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:taiga': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:old_growth_pine_taiga': ('minecraft:podzol', 'minecraft:dirt'),
'minecraft:snowy_taiga': ('minecraft:grass_block[snowy=true]', 'minecraft:dirt'),
'minecraft:snowy_plains': ('minecraft:snow_block', 'minecraft:dirt'),
'minecraft:ice_spikes': ('minecraft:snow_block', 'minecraft:packed_ice'),
'minecraft:frozen_peaks': ('minecraft:snow_block', 'minecraft:stone'),
'minecraft:jagged_peaks': ('minecraft:snow_block', 'minecraft:stone'),
'minecraft:stony_peaks': ('minecraft:stone', 'minecraft:stone'),
'minecraft:windswept_hills': ('minecraft:grass_block', 'minecraft:stone'),
'minecraft:desert': ('minecraft:sand', 'minecraft:sandstone'),
'minecraft:badlands': ('minecraft:red_sand', 'minecraft:terracotta'),
'minecraft:wooded_badlands': ('minecraft:coarse_dirt', 'minecraft:terracotta'),
'minecraft:savanna': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:jungle': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:bamboo_jungle': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:sparse_jungle': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:swamp': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:mangrove_swamp': ('minecraft:mud', 'minecraft:mud'),
'minecraft:mushroom_fields': ('minecraft:mycelium', 'minecraft:dirt'),
'minecraft:beach': ('minecraft:sand', 'minecraft:sand'),
'minecraft:snowy_beach': ('minecraft:sand', 'minecraft:sand'),
'minecraft:stony_shore': ('minecraft:stone', 'minecraft:stone'),
'minecraft:river': ('minecraft:sand', 'minecraft:dirt'),
'minecraft:pale_garden': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:grove': ('minecraft:snow_block', 'minecraft:dirt'),
'minecraft:snowy_slopes': ('minecraft:snow_block', 'minecraft:stone'),
'minecraft:savanna_plateau': ('minecraft:grass_block', 'minecraft:dirt'),
'minecraft:eroded_badlands': ('minecraft:red_sand', 'minecraft:terracotta'),
}
OCEANS = ['minecraft:ocean', 'minecraft:deep_ocean', 'minecraft:warm_ocean', 'minecraft:lukewarm_ocean',
'minecraft:deep_lukewarm_ocean', 'minecraft:cold_ocean', 'minecraft:deep_cold_ocean',
'minecraft:frozen_ocean', 'minecraft:deep_frozen_ocean', 'minecraft:river', 'minecraft:frozen_river']
CAVES = ['minecraft:lush_caves', 'minecraft:dripstone_caves', 'minecraft:deep_dark', 'minecraft:sulfur_caves']
NETHER = {
'minecraft:nether_wastes': 'minecraft:netherrack',
'minecraft:crimson_forest': 'minecraft:crimson_nylium',
'minecraft:warped_forest': 'minecraft:warped_nylium',
'minecraft:soul_sand_valley': 'minecraft:soul_sand',
'minecraft:basalt_deltas': 'minecraft:basalt',
}
END = ['minecraft:the_end', 'minecraft:end_highlands', 'minecraft:end_midlands', 'minecraft:small_end_islands',
'minecraft:end_barrens']
MOBS = {
'monster': ['zombie', 'skeleton', 'creeper', 'spider', 'enderman', 'witch', 'slime', 'drowned', 'husk', 'stray',
'zombie_villager', 'cave_spider', 'bogged', 'parched'],
'creature': ['cow', 'pig', 'sheep', 'chicken', 'horse', 'rabbit', 'wolf', 'fox', 'llama', 'polar_bear', 'goat',
'strider'],
'ambient': ['bat'],
'water_creature': ['squid', 'dolphin'],
'water_ambient': ['cod', 'salmon', 'tropical_fish', 'pufferfish'],
'axolotls': ['axolotl'],
'underground_water_creature': ['glow_squid'],
'nether': ['zombified_piglin', 'piglin', 'hoglin', 'ghast', 'magma_cube', 'skeleton', 'enderman', 'strider',
'blaze', 'wither_skeleton'],
}
CATEGORIES = ['monster', 'creature', 'ambient', 'axolotls', 'underground_water_creature', 'water_creature',
'water_ambient']
TORCH_LIGHT = [0, 0, 0, 1, 4, 7, 8, 9, 12, 14]
def java_next_int(seed, bound):
"""java.util.Random(seed).nextInt(bound)."""
mask = (1 << 48) - 1
state = (seed ^ 0x5DEECE66D) & mask
while True:
state = (state * 0x5DEECE66D + 0xB) & mask
bits = state >> 17
value = bits % bound
if bits - value + bound - 1 < 2**31:
return value
def slime_chunk(world_seed, cx, cz):
"""WorldgenRandom.seedSlimeChunk(cx, cz, seed, 987234911).nextInt(10) == 0."""
def i32(v):
return (v + 2**31) % 2**32 - 2**31
seed = (world_seed + i32(cx * cx * 4987142) + i32(cx * 5947611) + i32(cz * cz) * 4392871 + i32(cz * 389711)) ^ 987234911
return java_next_int(seed & (2**64 - 1), 10) == 0
def box(x0, y0, z0, x1, y1, z1):
return f'{x0},{y0},{z0},{x1},{y1},{z1}'
class World:
"""One case's world, written as the oracle's key=value tokens."""
def __init__(self, rng):
self.rng = rng
self.kv = {}
self.blocks, self.lights, self.biomes, self.starts, self.entities, self.players = [], [], [], [], [], []
self.sites = [] # (x, y, z, kind): open positions above a floor, in water or in lava
self.dim = 'minecraft:overworld'
self.surface = 64
self.min_y = -64
def block(self, b, state):
self.blocks.append(f'{b}/{state}')
def light(self, b, sky, block):
self.lights.append(f'{b}/{sky},{block}')
def tokens(self):
out = dict(self.kv)
for prefix, items in (('k', self.blocks), ('l', self.lights), ('b', self.biomes), ('s', self.starts),
('e', self.entities), ('p', self.players)):
for i, v in enumerate(items):
out[f'{prefix}{i}'] = v
return ' '.join(f'{k}={v}' for k, v in out.items())
def overworld(w, rng, biome=None, ocean=None):
lo, hi = -R, 16 + R - 1
w.kv['dim'] = 'minecraft:overworld'
w.kv['sea'] = 63
ocean = rng.random() < 0.2 if ocean is None else ocean
if ocean:
biome = biome or rng.choice(OCEANS)
floor = rng.randrange(28, 58)
w.kv['biome'] = biome
w.block(box(lo, -64, lo, hi, floor - 1, hi), 'minecraft:stone')
w.block(box(lo, floor - 1, lo, hi, floor - 1, hi), rng.choice(['minecraft:sand', 'minecraft:gravel', 'minecraft:clay']))
top = 62
water = 'minecraft:ice' if 'frozen' in biome and rng.random() < 0.5 else 'minecraft:water'
w.block(box(lo, floor, lo, hi, 62, hi), 'minecraft:water')
if water == 'minecraft:ice':
w.block(box(lo, 62, lo, hi, 62, hi), 'minecraft:ice')
for _ in range(6):
w.sites.append((rng.randrange(-4, 20), rng.randrange(floor, 62), rng.randrange(-4, 20), 'water'))
w.surface = 63
depth = 62 - floor
w.light(box(lo, -64, lo, hi, 62, hi), max(0, 15 - depth // 2) if rng.random() < 0.5 else 15, 0)
w.light(box(lo, -64, lo, hi, floor - 1, hi), 0, 0)
# An island.
if rng.random() < 0.3:
x, z = rng.randrange(-8, 20), rng.randrange(-8, 20)
w.block(box(x, floor, z, x + rng.randrange(3, 12), 64, z + rng.randrange(3, 12)), 'minecraft:sand')
return
biome = biome or rng.choice(list(OVERWORLD))
top, filler = OVERWORLD[biome]
surface = rng.randrange(58, 90)
w.surface = surface + 1
w.kv['biome'] = biome
w.block(box(lo, -64, lo, hi, surface - 4, hi), rng.choice(['minecraft:stone', 'minecraft:stone', 'minecraft:deepslate']))
w.block(box(lo, surface - 3, lo, hi, surface - 1, hi), filler)
w.block(box(lo, surface, lo, hi, surface, hi), top)
w.light(box(lo, -64, lo, hi, surface, hi), 0, 0)
for _ in range(4):
w.sites.append((rng.randrange(-2, 18), surface + 1, rng.randrange(-2, 18), 'surface'))
# Terraces and hills at other heights.
for _ in range(rng.randrange(0, 4)):
x, z, dy = rng.randrange(lo, hi), rng.randrange(lo, hi), rng.choice([-3, -2, -1, 1, 2, 3, 5])
sx, sz = rng.randrange(3, 20), rng.randrange(3, 20)
if dy > 0:
w.block(box(x, surface, z, x + sx, surface + dy - 1, z + sz), filler)
w.block(box(x, surface + dy, z, x + sx, surface + dy, z + sz), top)
else:
w.block(box(x, surface + dy + 1, z, x + sx, surface, z + sz), 'minecraft:air')
w.block(box(x, surface + dy, z, x + sx, surface + dy, z + sz), top)
w.light(box(x, surface + dy + 1, z, x + sx, surface, z + sz), 15, 0)
# Ponds, lava, trees and features on the surface.
for _ in range(rng.randrange(0, 3)):
x, z = rng.randrange(lo, hi), rng.randrange(lo, hi)
fluid = 'minecraft:water' if rng.random() < 0.8 else 'minecraft:lava'
d = rng.randrange(1, 4)
w.block(box(x, surface - d + 1, z, x + rng.randrange(2, 9), surface, z + rng.randrange(2, 9)), fluid)
w.sites.append((x, surface, z, 'water' if fluid == 'minecraft:water' else 'lava'))
for _ in range(rng.randrange(0, 4)):
x, z = rng.randrange(lo, hi), rng.randrange(lo, hi)
h = rng.randrange(4, 7)
leaves = rng.choice(['minecraft:oak_leaves', 'minecraft:spruce_leaves', 'minecraft:jungle_leaves', 'minecraft:birch_leaves'])
w.block(box(x - 2, surface + h - 2, z - 2, x + 2, surface + h + 1, z + 2), leaves)
w.block(box(x, surface + 1, z, x, surface + h, z), 'minecraft:oak_log')
w.light(box(x - 2, surface + 1, z - 2, x + 2, surface + h - 3, z + 2), 14, 0)
for _ in range(rng.randrange(0, 6)):
x, z = rng.randrange(lo, hi), rng.randrange(lo, hi)
thing = rng.choice(['minecraft:short_grass', 'minecraft:tall_grass[half=lower]', 'minecraft:snow[layers=1]',
'minecraft:oak_slab[type=bottom]', 'minecraft:glass', 'minecraft:rail', 'minecraft:torch',
'minecraft:sweet_berry_bush', 'minecraft:powder_snow', 'minecraft:cobweb',
'minecraft:white_carpet', 'minecraft:oak_fence', 'minecraft:redstone_block', 'minecraft:magma_block'])
w.block(box(x, surface + 1, z, x + rng.randrange(0, 5), surface + 1, z + rng.randrange(0, 5)), thing)
# Caves: lit or dark rooms underground, some with water, a cave biome.
for _ in range(rng.choice([0, 1, 2, 2, 3, 4, 5])):
x, z = rng.randrange(-20, 14), rng.randrange(-20, 14)
y = rng.randrange(-60, surface - 6)
sx, sy, sz = rng.randrange(4, 24), rng.randrange(2, 8), rng.randrange(4, 24)
y1 = min(y + sy, surface - 2)
w.block(box(x, y, z, x + sx, y1, z + sz), 'minecraft:cave_air' if rng.random() < 0.5 else 'minecraft:air')
w.light(box(x, y, z, x + sx, y1, z + sz), 0, rng.choice(TORCH_LIGHT))
wet = rng.random() < 0.35
if wet:
w.block(box(x, y, z, x + sx, y + rng.randrange(1, 4), z + sz), 'minecraft:water')
if rng.random() < 0.3:
w.block(box(x, y - 1, z, x + sx, y - 1, z + sz), rng.choice(['minecraft:clay', 'minecraft:moss_block', 'minecraft:sculk', 'minecraft:dripstone_block', 'minecraft:clay']))
if rng.random() < 0.45:
w.biomes.append(f'{box(x - 2, y - 2, z - 2, x + sx + 2, y1 + 2, z + sz + 2)}/{rng.choice(CAVES)}')
for _ in range(3):
w.sites.append((rng.randrange(x, x + sx + 1), y + (rng.randrange(0, 2) if wet else 0), rng.randrange(z, z + sz + 1), 'water' if wet else 'cave'))
if rng.random() < 0.2:
# An opening to the sky.
w.block(box(x + 1, y1, z + 1, x + 3, surface, z + 3), 'minecraft:air')
w.light(box(x + 1, y, z + 1, x + 3, surface, z + 3), 15, 0)
def nether(w, rng, biome=None):
lo, hi = -R, 16 + R - 1
biome = biome or rng.choice(list(NETHER))
w.kv['dim'] = 'minecraft:the_nether'
w.kv['sea'] = 32
w.kv['biome'] = biome
w.kv['sky'] = 0
floor = rng.randrange(28, 80)
w.surface = 128
w.block(box(lo, 0, lo, hi, 0, hi), 'minecraft:bedrock')
w.block(box(lo, 1, lo, hi, floor - 1, hi), 'minecraft:netherrack')
w.block(box(lo, floor, lo, hi, floor, hi), NETHER[biome])
w.block(box(lo, rng.randrange(100, 120), lo, hi, 126, hi), 'minecraft:netherrack')
w.block(box(lo, 127, lo, hi, 127, hi), 'minecraft:bedrock')
w.light(box(lo, 0, lo, hi, 127, hi), 0, rng.choice([0, 0, 3, 7, 11]))
for _ in range(4):
w.sites.append((rng.randrange(-2, 18), floor + 1, rng.randrange(-2, 18), 'surface'))
if floor <= 34 or rng.random() < 0.4:
x, z = rng.randrange(lo, hi), rng.randrange(lo, hi)
w.block(box(x, min(floor, 20), z, x + rng.randrange(6, 30), 31, z + rng.randrange(6, 30)), 'minecraft:lava')
w.sites.append((x + 2, 31, z + 2, 'lava'))
w.light(box(x, 20, z, x + 30, 40, z + 30), 0, 15)
for _ in range(rng.randrange(0, 4)):
x, z = rng.randrange(lo, hi), rng.randrange(lo, hi)
y = rng.randrange(floor - 10, floor + 20)
w.block(box(x, y, z, x + rng.randrange(3, 14), y, z + rng.randrange(3, 14)),
rng.choice(['minecraft:netherrack', 'minecraft:nether_wart_block', 'minecraft:soul_soil', 'minecraft:magma_block',
'minecraft:glowstone', 'minecraft:blackstone', 'minecraft:nether_bricks', 'minecraft:fire']))
if rng.random() < 0.3:
x, z = rng.randrange(lo, hi), rng.randrange(lo, hi)
w.biomes.append(f'{box(x, 0, z, x + rng.randrange(8, 40), 127, z + rng.randrange(8, 40))}/{rng.choice(list(NETHER))}')
return floor
def end(w, rng):
lo, hi = -R, 16 + R - 1
w.kv['dim'] = 'minecraft:the_end'
w.kv['sea'] = 0
w.kv['sky'] = 0
w.kv['biome'] = rng.choice(END)
top = rng.randrange(40, 70)
w.surface = top + 1
w.block(box(lo, top - rng.randrange(5, 30), lo, hi, top, hi), 'minecraft:end_stone')
w.light(box(lo, 0, lo, hi, 255, hi), 0, rng.choice([0, 0, 5, 14]))
for _ in range(4):
w.sites.append((rng.randrange(-2, 18), top + 1, rng.randrange(-2, 18), 'surface'))
def structures(w, rng):
dim = w.kv['dim']
s = w.surface
if dim == 'minecraft:the_nether':
if rng.random() < 0.6:
# Fortress corridors on nether bricks (FORTRESS_ENEMIES and the piece override).
y = rng.randrange(40, 80)
pieces = []
for _ in range(rng.randrange(1, 4)):
x, z = rng.randrange(-30, 30), rng.randrange(-30, 30)
along = rng.random() < 0.5
x1, z1 = (x + rng.randrange(10, 40), z + 4) if along else (x + 4, z + rng.randrange(10, 40))
pieces.append(box(x, y, z, x1, y + 6, z1))
w.block(box(x, y, z, x1, y, z1), 'minecraft:nether_bricks')
w.block(box(x, y + 1, z, x1, y + 5, z1), 'minecraft:air')
w.light(box(x, y + 1, z, x1, y + 5, z1), 0, rng.choice([0, 7, 11]))
w.block(box(x, y + 6, z, x1, y + 6, z1), 'minecraft:nether_bricks')
w.sites.append((rng.randrange(x, x1 + 1), y + 1, rng.randrange(z, z1 + 1), 'structure'))
w.starts.append('minecraft:fortress/' + ';'.join(pieces))
if rng.random() < 0.2:
x, z = rng.randrange(-20, 20), rng.randrange(-20, 20)
w.starts.append(f'minecraft:bastion_remnant/{box(x, 30, z, x + 30, 80, z + 30)}')
return
if dim != 'minecraft:overworld':
return
biome = w.kv['biome']
roll = rng.random()
x, z = rng.randrange(-24, 24), rng.randrange(-24, 24)
if biome in ('minecraft:swamp', 'minecraft:mangrove_swamp') and roll < 0.7:
# Swamp hut: witches and cats only in its piece.
y = s + 1
w.block(box(x, y, z, x + 6, y, z + 8), 'minecraft:spruce_planks')
w.block(box(x + 1, y + 1, z + 1, x + 5, y + 4, z + 7), 'minecraft:air')
w.light(box(x + 1, y + 1, z + 1, x + 5, y + 4, z + 7), rng.choice([0, 3, 9]), 0)
w.block(box(x, y + 5, z, x + 6, y + 5, z + 8), 'minecraft:spruce_planks')
w.starts.append(f'minecraft:swamp_hut/{box(x, y, z, x + 6, y + 6, z + 8)}')
w.sites.append((x + 3, y + 1, z + 4, 'structure'))
elif 'ocean' in biome and roll < 0.6:
w.starts.append(f'minecraft:monument/{box(x, 39, z, x + 57, 61, z + 57)}')
w.sites.append((x + 8, rng.randrange(40, 61), z + 8, 'structure'))
elif roll < 0.15:
w.starts.append(f'minecraft:pillager_outpost/{box(x, s, z, x + 8, s + 20, z + 8)};{box(x + 10, s, z + 2, x + 14, s + 5, z + 6)}')
w.sites.append((x + 4, s, z + 4, 'structure'))
elif roll < 0.25:
y = rng.randrange(-40, -10)
w.block(box(x, y, z, x + 20, y + 8, z + 20), 'minecraft:air')
w.block(box(x, y - 1, z, x + 20, y - 1, z + 20), 'minecraft:tuff_bricks')
w.light(box(x, y, z, x + 20, y + 8, z + 20), 0, 0)
w.starts.append(f'minecraft:trial_chambers/{box(x, y - 1, z, x + 20, y + 9, z + 20)}')
w.sites.append((x + 5, y, z + 5, 'structure'))
elif roll < 0.32:
y = rng.randrange(-52, -30)
w.block(box(x, y, z, x + 30, y + 10, z + 30), 'minecraft:air')
w.block(box(x, y - 1, z, x + 30, y - 1, z + 30), 'minecraft:deepslate_tiles')
w.light(box(x, y, z, x + 30, y + 10, z + 30), 0, 0)
w.biomes.append(f'{box(x - 4, y - 4, z - 4, x + 34, y + 14, z + 34)}/minecraft:deep_dark')
w.starts.append(f'minecraft:ancient_city/{box(x, y - 1, z, x + 30, y + 11, z + 30)}')
w.sites.append((x + 5, y, z + 5, 'structure'))
elif roll < 0.4:
w.starts.append(f'minecraft:village_plains/{box(x, s - 2, z, x + 12, s + 8, z + 12)}')
def mob_entities(w, rng):
dim = w.kv['dim']
pool = MOBS['nether'] if dim == 'minecraft:the_nether' else sum((MOBS[c] for c in CATEGORIES if c in MOBS), [])
n = rng.choice([0, 0, 1, 3, 6, 12, 25, 80])
for _ in range(n):
t = rng.choice(pool)
x, z = rng.uniform(-R + 2, 16 + R - 2), rng.uniform(-R + 2, 16 + R - 2)
y = rng.choice([w.surface, w.surface, rng.randrange(w.min_y + 2, w.surface + 1)])
persistent = '/p' if rng.random() < 0.2 else ''
w.entities.append(f'minecraft:{t}/{x:.3f},{y},{z:.3f}{persistent}')
if w.kv.get('biome') in ('minecraft:soul_sand_valley', 'minecraft:warped_forest') or any('soul_sand_valley' in b or 'warped' in b for b in w.biomes):
for _ in range(rng.randrange(0, 10)):
t = rng.choice(['skeleton', 'ghast', 'enderman', 'strider'])
w.entities.append(f'minecraft:{t}/{rng.uniform(-10, 26):.3f},{w.sites[0][1]},{rng.uniform(-10, 26):.3f}')
# Clusters right where spawns happen (obstruction and spawn potential).
if rng.random() < 0.3:
t = rng.choice(pool)
for _ in range(rng.randrange(1, 8)):
w.entities.append(f'minecraft:{t}/{rng.randrange(0, 16) + 0.5},{w.surface},{rng.randrange(0, 16) + 0.5}')
def place_players(w, rng):
count = rng.choice([1, 1, 1, 1, 2, 3])
for _ in range(count):
kind = rng.random()
if kind < 0.75:
# 24 to ~100 blocks from the chunk: most attempts are allowed.
ang, dist = rng.uniform(0, 6.283), rng.uniform(26, 100)
elif kind < 0.87:
ang, dist = rng.uniform(0, 6.283), rng.uniform(0, 30)
else:
ang, dist = rng.uniform(0, 6.283), rng.uniform(100, 200)
import math
x, z = 8 + dist * math.cos(ang), 8 + dist * math.sin(ang)
y = w.surface + rng.choice([0, 0, 5, 30, -20])
mode = rng.choice(['survival'] * 8 + ['creative', 'adventure', 'spectator'])
w.players.append(f'{x:.3f},{y},{z:.3f}/{mode}')
def common(w, rng, seed):
w.kv['seed'] = seed
w.kv['wseed'] = rng.randrange(-2**63, 2**63)
if w.kv['dim'] == 'minecraft:overworld':
w.kv['darken'] = rng.choice([0, 0, 2, 4, 7, 11, 11, 11, 11, 11])
if rng.random() < 0.08:
w.kv['thunder'] = 1
if rng.random() < 0.3:
w.kv['slime'] = rng.choice([0.0, 0.125, 0.25, 0.5])
w.kv['difficulty'] = rng.choice(['normal', 'normal', 'hard', 'easy', 'peaceful'])
if rng.random() < 0.15:
w.kv['respawn'] = f'{rng.randrange(-20, 36)},{w.surface},{rng.randrange(-20, 36)}/{w.kv["dim"]}'
if rng.random() < 0.2:
w.kv['unloaded'] = ';'.join(f'{rng.choice([-1, 0, 1])},{rng.choice([-1, 0, 1])}' for _ in range(rng.randrange(1, 5)))
def make_world(rng, seed, dim=None, biome=None, ocean=None):
w = World(rng)
dim = dim or rng.choices(['overworld', 'nether', 'end'], [70, 22, 8])[0]
if dim == 'overworld':
overworld(w, rng, biome=biome, ocean=ocean)
elif dim == 'nether':
w.min_y = 0
nether(w, rng, biome=biome)
else:
w.min_y = 0
end(w, rng)
structures(w, rng)
mob_entities(w, rng)
place_players(w, rng)
common(w, rng, seed)
return w
def corpus():
rng = random.Random(0x4E5350)
cases = []
# Whole chunk ticks.
for k in range(3000):
w = make_world(rng, rng.randrange(-2**47, 2**47))
if rng.random() < 0.2:
w.kv['chunkcount'] = rng.choice([0, 1, 4, 17, 40, 100, 200, 289, 578])
w.kv['enemies'] = 1 if rng.random() < 0.9 else 0
w.kv['persistent'] = 1 if rng.random() < 0.5 else 0
cases.append(f'chunk/{k} mode=chunk {w.tokens()}')
# Chosen starts at sites: surfaces, cave floors, water, lava, structure floors.
for k in range(7000):
w = make_world(rng, rng.randrange(-2**47, 2**47))
dim = w.kv['dim']
x, y, z, kind = rng.choice(w.sites)
if kind == 'structure' and rng.random() < 0.5:
x, z = x + rng.randrange(-3, 4), z + rng.randrange(-3, 4)
if rng.random() < 0.1:
y = rng.randrange(w.min_y + 1, w.surface + 2)
if dim == 'minecraft:the_nether':
category = 'creature' if kind == 'lava' or rng.random() < 0.2 else 'monster'
elif dim == 'minecraft:the_end':
category = 'monster'
elif kind == 'water':
category = rng.choice(['water_creature', 'water_ambient', 'axolotls', 'underground_water_creature', 'monster'])
elif kind == 'cave':
category = rng.choice(['monster', 'monster', 'ambient', 'ambient', 'creature'])
elif kind == 'structure':
category = rng.choice(['monster', 'monster', 'creature', 'ambient', 'water_ambient'])
else:
category = rng.choice(['monster', 'creature', 'creature', 'ambient'])
if rng.random() < 0.05:
category = rng.choice(CATEGORIES)
cases.append(f'pos/{k} mode=pos cat={category} start={x},{y},{z} {w.tokens()}')
# Targeted nights and places for the rarer types.
targets = [
('minecraft:desert', False, 'surface', 'monster'), ('minecraft:desert', False, 'surface', 'creature'),
('minecraft:snowy_plains', False, 'surface', 'monster'), ('minecraft:ice_spikes', False, 'surface', 'creature'),
('minecraft:swamp', False, 'surface', 'monster'), ('minecraft:mangrove_swamp', False, 'surface', 'monster'),
('minecraft:jungle', False, 'surface', 'monster'), ('minecraft:bamboo_jungle', False, 'surface', 'monster'),
('minecraft:plains', False, 'surface', 'monster'), ('minecraft:savanna', False, 'surface', 'creature'),
('minecraft:badlands', False, 'surface', 'creature'), ('minecraft:warm_ocean', True, 'water', 'water_ambient'),
('minecraft:lukewarm_ocean', True, 'water', 'water_creature'), ('minecraft:deep_ocean', True, 'water', 'monster'),
('minecraft:frozen_ocean', True, 'water', 'creature'), ('minecraft:lush_caves', None, 'cave', 'axolotls'),
('minecraft:sulfur_caves', None, 'cave', 'monster'), ('minecraft:dripstone_caves', None, 'cave', 'monster'),
('minecraft:crimson_forest', 'nether', 'surface', 'monster'), ('slime', None, 'cave', 'monster'),
('minecraft:river', True, 'water', 'monster'),
]
for k in range(4000):
biome, ocean, kind, category = rng.choice(targets)
if ocean == 'nether':
w = make_world(rng, rng.randrange(-2**47, 2**47), dim='nether', biome=biome)
elif kind == 'cave':
w = make_world(rng, rng.randrange(-2**47, 2**47), dim='overworld', ocean=False)
else:
w = make_world(rng, rng.randrange(-2**47, 2**47), dim='overworld', biome=biome, ocean=ocean)
w.kv['darken'] = 11 if category == 'monster' else rng.choice([0, 0, 4, 11])
w.kv.pop('thunder', None)
sites = [t for t in w.sites if t[3] == kind] or w.sites
x, y, z, _ = rng.choice(sites)
if kind == 'cave':
# A dark room under the start, in the cave biome (or a slime chunk).
w.block(box(x - 6, y, z - 6, x + 6, y + 4, z + 6), 'minecraft:cave_air')
floor = 'minecraft:clay' if category == 'axolotls' else rng.choice(['minecraft:stone', 'minecraft:deepslate'])
w.block(box(x - 6, y - 1, z - 6, x + 6, y - 1, z + 6), floor)
if category == 'axolotls' or biome == 'minecraft:dripstone_caves' and rng.random() < 0.5:
w.block(box(x - 6, y, z - 6, x + 6, y + 2, z + 6), 'minecraft:water')
w.light(box(x - 6, y, z - 6, x + 6, y + 4, z + 6), 0, rng.choice([0, 0, 0, 3]))
if biome == 'slime':
y = min(y, rng.randrange(-50, 38))
w.block(box(x - 6, y, z - 6, x + 6, y + 4, z + 6), 'minecraft:cave_air')
w.block(box(x - 6, y - 1, z - 6, x + 6, y - 1, z + 6), 'minecraft:stone')
w.light(box(x - 6, y, z - 6, x + 6, y + 4, z + 6), 0, 0)
while not slime_chunk(w.kv['wseed'], 0, 0):
w.kv['wseed'] = rng.randrange(-2**63, 2**63)
else:
w.biomes.append(f'{box(x - 8, y - 3, z - 8, x + 8, y + 6, z + 8)}/{biome}')
if biome in ('minecraft:swamp', 'minecraft:mangrove_swamp'):
w.kv['slime'] = rng.choice([0.0, 0.25, 0.5])
cases.append(f'target/{k} mode=pos cat={category} start={x},{y},{z} {w.tokens()}')
# Chunk generation: creature packs placed on the surface.
for k in range(1500):
w = World(rng)
dim = rng.choices(['overworld', 'nether'], [85, 15])[0]
if dim == 'overworld':
biome = rng.choice(list(OVERWORLD) + ['minecraft:frozen_ocean', 'minecraft:beach'] * 2)
if biome in OVERWORLD:
overworld(w, rng, biome=biome, ocean=False)
else:
overworld(w, rng, biome=biome, ocean=True)
else:
w.min_y = 0
nether(w, rng)
common(w, rng, rng.randrange(-2**47, 2**47))
w.kv['gseed'] = rng.randrange(-2**47, 2**47)
if rng.random() < 0.05:
w.kv['rules'] = 0
w.kv['chunk'] = f'{rng.randrange(-3, 3)},{rng.randrange(-3, 3)}'
cases.append(f'gen/{k} mode=gen {w.tokens()}')
return cases
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--prepare', action='store_true')
args = parser.parse_args()
build = lab.LOCAL / 'rust-natural-spawn-parity'
build.mkdir(parents=True, exist_ok=True)
if args.prepare:
lab.prepare()
lock, jars, libraries = base.verify_artifacts()
resources = lab.LOCAL / 'horizon-client/26.3'
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java'
sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/natural_spawn_fixture.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs']
tested = base.source_hashes(sources)
inputs = build / 'inputs.txt'
cases = corpus()
inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8')
classes = build / 'classes'
classes.mkdir(exist_ok=True)
deps = os.pathsep.join(map(str, libraries))
def run(command, name):
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'),
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx3G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaNaturalSpawnOracle', inputs, build / 'server.txt'], 'server')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'natural_spawn_fixture'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/natural_spawn_fixture'
run([binary, resources, inputs, build / 'rust.txt'], 'rust')
vanilla = (build / 'server.txt').read_text().splitlines()
errors = [l for l in vanilla if ' error ' in l]
if errors:
raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}')
rust = (build / 'rust.txt').read_text().splitlines()
bad = [(a, b) for a, b in zip(vanilla, rust) if a != b]
if bad or len(vanilla) != len(rust):
report = '\n'.join(f' vanilla {a[:1500]}\n rust {b[:1500]}' for a, b in bad[:20])
raise SystemExit(f'{len(bad)} of {len(vanilla)} cases differ (rust {len(rust)} lines):\n{report}')
base.ensure_sources_unchanged(sources, tested)
spawns = sum(line.count(' ; spawn ') for line in vanilla)
attempts = sum(line.count(' ; try ') + line.count(' ; col ') for line in vanilla)
tests = sum(line.count(' ; test ') for line in vanilla)
lab.write_json(build / 'report.json', {
'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases),
'attempts': attempts, 'type_checks_passed': tests, 'spawns': spawns, 'sources_sha256': tested,
'scope': 'NaturalSpawner: createState (counts, spawn potential, local caps), getFilteredSpawningCategories, '
'spawnForChunk, spawnCategoryForPosition (distance and respawn checks, getRandomSpawnMobAt over mobsAt: '
'fortress bounds, structure spawn overrides, biome spawns; isValidSpawnPostitionForType with '
'SpawnPlacements; isValidPositionForMob with each class\'s checkSpawnRules, checkSpawnObstruction and '
'removeWhenFarAway; cluster and group sizes) and spawnMobsForChunkGeneration, with every random draw. '
'finalizeSpawn runs with a fixed random in the oracle; its own outcomes are not compared.'})
print(f'{len(cases):,} natural spawn cases match vanilla ({attempts:,} attempts, {tests:,} type checks passed, '
f'{spawns:,} spawns)')
if __name__ == '__main__':
main()
+33 -18
View File
@@ -59,7 +59,7 @@ IGNORED = {
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'wasOnGround|Fire|Air|DeathTime|Fuse|life|inGround|ticks_in_ground|Time)$': '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',
@@ -72,12 +72,6 @@ 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)',
r'^entity\.attributes': 'Horizon derives the attribute list of a horse from its own model',
r'^entity\.Brain\.memories': 'Horizon gives villagers memories (meeting point) that vanilla had not formed yet',
}
SUSPICIOUS = re.compile(
@@ -85,7 +79,7 @@ SUSPICIOUS = re.compile(
r'Recreating|upgrad|DataFix|out of bounds|missing|Mismatch|Discarding)', re.IGNORECASE)
BENIGN = re.compile(r'(Unpacking |OFFLINE/INSECURE|online-mode|authenticate usernames|hackers|'
r'Failed to load properties|Failed to load eula|Unknown or incomplete command|'
r'Can.t keep up|Ignoring unknown|^WARNING: |No key layers|has the following)')
r'Can.t keep up|Ignoring unknown|^WARNING: |No key layers|has the following|udev library)')
# ---------------------------------------------------------------- vanilla server
@@ -409,7 +403,14 @@ def compare_chunks(vanilla, horizon, report):
report.append((f'{path} @{key}', p, q))
def compare_entities(vanilla, horizon, report):
def chunk_of(entity):
pos = entity.get('Pos')
pos = pos[1] if isinstance(pos, tuple) else pos
x, z = (p[1] if isinstance(p, tuple) else p for p in (pos[0], pos[2]))
return int(x // 16), int(z // 16)
def compare_entities(vanilla, horizon, report, chunks=None):
def collect(regions):
out = {}
for key, root in regions.items():
@@ -418,11 +419,13 @@ def compare_entities(vanilla, horizon, report):
out[uuid] = e
return out
a, b = collect(vanilla), collect(horizon)
# Entities Horizon adds (chunk-generation spawns in the chunks vanilla never
# generated) are not part of the scene.
extra = [u for u in b if u not in a and not (u and u[0] == UUID_BASE)]
# Entities Horizon adds in the chunks vanilla never generated (chunk-generation
# spawns) are not part of the scene; anywhere else they are a difference.
vanilla_chunks = {chunk_of(e) for e in a.values()} | set(chunks or ())
extra = [u for u in b if u not in a and not (u and u[0] == UUID_BASE)
and chunk_of(b[u]) not in vanilla_chunks]
if extra:
print(f' note: Horizon saved {len(extra)} entities that are not in the scene (generated chunks)')
print(f' note: Horizon saved {len(extra)} entities in chunks vanilla never generated')
for uuid in extra:
del b[uuid]
for uuid in sorted(set(a) | set(b), key=str):
@@ -460,7 +463,8 @@ def compare_worlds(vanilla, horizon):
report = []
va, ha = dimension(vanilla), dimension(horizon)
compare_chunks(load_regions(va / 'region'), load_regions(ha / 'region'), report)
compare_entities(load_regions(va / 'entities'), load_regions(ha / 'entities'), report)
chunks = {(k[1], k[2]) for k in load_regions(va / 'region')}
compare_entities(load_regions(va / 'entities'), load_regions(ha / 'entities'), report, chunks)
for rel in ['level.dat'] + sorted(
str(p.relative_to(vanilla)) for pattern in ('data/**/*.dat', 'players/**/*.dat')
for p in vanilla.glob(pattern)):
@@ -497,7 +501,7 @@ def summarize(report):
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--keep', action='store_true')
parser.add_argument('--bin-dir', default=str(ROOT / 'target' / 'fast'))
parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build them with the fast profile)')
parser.add_argument('--vanilla', help='an existing vanilla world folder (skips generation)')
parser.add_argument('--horizon', help='an existing Horizon-saved world folder (skips the Horizon run)')
parser.add_argument('--skip-vanilla-load', action='store_true')
@@ -520,7 +524,11 @@ def main():
if args.horizon:
h = Path(args.horizon)
else:
h = horizon_resave(v0, RUN / 'h', Path(args.bin_dir))
bin_dir = Path(args.bin_dir) if args.bin_dir else None
if bin_dir is None:
subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bins'], cwd=ROOT, check=True)
bin_dir = ROOT / os.environ.get('CARGO_TARGET_DIR', 'target') / 'fast'
h = horizon_resave(v0, RUN / 'h', bin_dir)
print('comparing', v0, 'with', h)
report = compare_worlds(v0, h)
failures += summarize(report)
@@ -531,13 +539,17 @@ def main():
shutil.rmtree(RUN / 'v0view', ignore_errors=True)
shutil.copytree(v0, RUN / 'v0view' / 'world')
views0, problems0 = view_of_world(RUN / 'v0view')
untimed = re.compile(r'^\[[0-9:]+\] ')
seen0 = {untimed.sub('', line) for line in problems0}
for line in problems1:
if line not in problems0:
if untimed.sub('', line) not in seen0:
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|triggered|state_updating_resumes_at|LastExecution|last_vibration_frequency|warning_level): -?[0-9]+[a-zA-Z]?')
volatile2 = re.compile(r'(RecipesUsed: \{[^}]*\}|listener: \{.*\}(?=, x))')
# The lit furnace keeps smelting while each game runs: its slots move on.
volatile_items = re.compile(r'Items: \[[^\]]*\]')
for label in views0:
if label.startswith('entity'):
# Entity data moves with the simulation: only require vanilla to load it.
@@ -547,7 +559,10 @@ def main():
print(f'VANILLA cannot find {label} in the Horizon save')
failures += 1
continue
if volatile2.sub('', volatile.sub('', views0[label])) != volatile2.sub('', volatile.sub('', views1.get(label, ''))):
def stable(text):
text = volatile2.sub('', volatile.sub('', text))
return volatile_items.sub('', text) if label == 'block 10 furnace' else text
if stable(views0[label]) != stable(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)')
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Compare the situational music choice with the vanilla 26.3 client.
The oracle calls the real `Minecraft.getSituationalMusic` and
`getMusicVolume` with the open screen (none or the credits), the boss
overlay's bars (none, darkening, music), the player (absent, or in a dimension
with creative abilities and an underwater state) and a real camera
`EnvironmentAttributeProbe` over the dimension and biome attribute layers of
the vanilla data pack. Horizon's `Situation` with `MusicTables` answers the
same, for every dimension type x biome and every combination of the rest.
"""
import itertools
try:
from . import audio_harness as h
except ImportError:
import audio_harness as h
def fixtures():
data = h.RESOURCES / 'data/minecraft'
biomes = sorted('minecraft:' + p.stem for p in (data / 'worldgen/biome').glob('*.json'))
dimensions = ['minecraft:overworld', 'minecraft:the_nether', 'minecraft:the_end']
lines = []
for screen, boss in itertools.product(['none', 'win'], ['none', 'dark', 'music', 'dark+music']):
lines.append(f'{screen} 0 minecraft:overworld minecraft:plains {boss} 0 0 0')
for d, b in itertools.product(dimensions, biomes):
for screen, boss, instabuild, mayfly, water in itertools.product(['none', 'win'], ['none', 'dark', 'music'], '01', '01', '01'):
lines.append(f'{screen} 1 {d} {b} {boss} {instabuild} {mayfly} {water}')
return lines
def main():
lines = fixtures()
matched, report = h.run_harness(
'situational-music', 'VanillaSituationalMusicOracle', 'situational_music_fixture', ''.join(l + '\n' for l in lines),
extra_sources=[h.lab.ROOT / 'crates/horizon-client/src/music.rs'], rust_args=[h.RESOURCES],
scope='Real Minecraft.getSituationalMusic/getMusicVolume: screen music (credits), menu without a player, End boss music from '
'the boss overlay, BACKGROUND_MUSIC and MUSIC_VOLUME through a real camera EnvironmentAttributeProbe, creative abilities '
'(instabuild && mayfly) and underwater selection, for every dimension x biome.')
print(f'{matched:,} situational music lines match the pinned client: {report}', flush=True)
if __name__ == '__main__':
main()
+247
View File
@@ -0,0 +1,247 @@
#!/usr/bin/env python3
"""Compare the sound engine's bookkeeping with the vanilla 26.3 client.
The oracle runs the real `SoundManager`/`SoundEngine` on OpenAL Soft's "No
Output" device (see VanillaSoundRig) and replays scripts of plays (simple,
biome loop, underwater loop and sub-sound instances), stops (by instance, by
sound and/or source, all), category gains, source volume options and
refreshes, channel ends, delayed and queued sounds, pauses and client ticks.
After every step it prints each instance's `isActive` and the AL source the
engine configured (state, gain, pitch, position, relative, looping, distance
model, max distance, rolloff, reference distance), the subtitle notifications
and the channel pool counts. Horizon's `SoundEngine` replays the scripts
against a backend that records the same AL source fields.
"""
import json
import random
try:
from . import audio_harness as h
except ImportError:
import audio_harness as h
def dbits(v):
import struct
return struct.pack('>d', v).hex()
class Script:
def __init__(self, events, streams):
self.lines = []
self.events, self.streams = events, streams
def add(self, *parts):
self.lines.append(' '.join(map(str, parts)))
def play(self, name, event, source=4, volume=1.0, pitch=1.0, at=(0.0, 0.0, 0.0), looping=0, delay=0, linear=True, relative=0, seed=0, kind='simple'):
self.add('play', name, kind, event, source, h.bits(volume), h.bits(pitch), *map(dbits, at), looping, delay,
'linear' if linear else 'none', relative, seed)
def tick(self, n=1, paused=0):
for _ in range(n):
self.add('tick', paused)
def reset(self):
self.add('stopmatch', '-', '-')
for source in range(11):
self.add('volume', source, h.bits(1.0))
self.tick()
def scripted(s):
stone, cave, click = 'minecraft:block.stone.break', 'minecraft:ambient.cave', 'minecraft:ui.button.click'
music, loop, uloop = 'minecraft:music.game', 'minecraft:ambient.crimson_forest.loop', 'minecraft:ambient.underwater.loop'
# Positional and relative sounds, lifetimes and channel ends.
s.play('a', stone, 4, 1.0, 0.8, (10.5, 64.0, -3.25), seed=5)
s.play('b', click, 10, 0.25, 1.0, linear=False, relative=1, seed=6)
s.play('c', cave, 8, 4.0, 1.0, (100.0, 20.0, 100.0), seed=7)
s.play('d', stone, 4, 1.5, 3.0, (0.5, 0.5, 0.5), seed=8)
s.play('e', stone, 4, 0.5, 0.1, (1.0, 2.0, 3.0), seed=9)
s.tick(3)
s.add('finish', 'a')
s.tick(25)
s.add('finish', 'b')
s.add('stop', 'c')
s.tick(2)
s.reset()
# Volumes: options, category gains, refreshes, silent starts.
s.add('volume', 4, h.bits(0.5))
s.add('volume', 0, h.bits(0.75))
s.play('a', stone, 4, 1.0, 1.0, (1.0, 1.0, 1.0), seed=1)
s.add('volume', 4, h.bits(0.0))
s.play('b', stone, 4, 1.0, 1.0, (1.0, 1.0, 1.0), seed=2)
s.add('volume', 1, h.bits(0.0))
s.play('m', music, 1, 1.0, 1.0, linear=False, relative=1, seed=3)
s.add('refresh', 4)
s.add('volume', 4, h.bits(0.3))
s.add('refresh', 0)
s.add('gain', 1, h.bits(0.5))
s.add('gain', 1, h.bits(1.5))
s.add('gain', 4, h.bits(-0.2))
s.add('volume', 1, h.bits(1.0))
s.add('refresh', 1)
s.tick(2)
s.add('volume', 0, h.bits(2.0))
s.add('refresh', 0)
s.reset()
# Biome loops: fades, crossfade, stopping, removal.
s.play('l1', loop, kind='loop', seed=11)
s.add('fade', 'l1', 'in')
s.tick(45)
s.play('l2', 'minecraft:ambient.warped_forest.loop', kind='loop', seed=12)
s.add('fade', 'l1', 'out')
s.add('fade', 'l2', 'in')
s.tick(50)
s.add('fade', 'l2', 'out')
s.tick(10)
s.add('fade', 'l2', 'in')
s.tick(60)
s.add('volume', 8, h.bits(0.0))
s.play('l3', loop, kind='loop', seed=13)
s.tick(3)
s.reset()
# Underwater loop and sub-sounds.
s.add('player', 1, 0)
s.play('u', uloop, kind='uloop', seed=21)
s.play('v', 'minecraft:ambient.underwater.loop.additions.rare', kind='usub', seed=22)
s.tick(50)
s.add('player', 0, 0)
s.tick(5)
s.add('player', 1, 0)
s.tick(5)
s.add('player', 0, 0)
s.tick(30)
s.add('player', 1, 1)
s.play('u2', uloop, kind='uloop', seed=23)
s.tick(3)
s.add('player', 0, 0)
s.reset()
# Queued tickables, delayed and manually looped sounds.
s.play('q', loop, kind='loop', seed=31)
s.add('stop', 'q')
s.tick(25)
s.add('queue', 'q')
s.add('fade', 'q', 'in')
s.tick(3)
s.play('w', stone, 4, 1.0, 1.0, (2.0, 2.0, 2.0), seed=32)
s.add('delayed', 'w', 5)
s.tick(7)
s.play('r', stone, 4, 1.0, 1.0, (3.0, 3.0, 3.0), looping=1, delay=4, seed=33)
s.tick(22)
s.add('finish', 'r')
s.tick(8)
s.add('finish', 'r')
s.tick(6)
s.play('n', stone, 4, 1.0, 1.0, (3.0, 3.0, 3.0), looping=1, seed=34)
s.tick(2)
s.reset()
# Stopping by source and sound, pauses.
s.play('a', stone, 4, seed=41)
s.play('b', stone, 5, seed=42)
s.play('c', cave, 8, seed=43)
s.play('m', music, 1, linear=False, relative=1, seed=44)
s.play('u', click, 10, linear=False, relative=1, seed=45)
s.add('pause')
s.tick(1, paused=1)
s.add('stop', 'm')
s.tick(1, paused=1)
s.add('resume')
s.add('stopmatch', stone, '-')
s.tick(25)
s.add('stopmatch', '-', 8)
s.add('stopmatch', click, 4)
s.add('stopmatch', click, 10)
s.tick(2)
s.reset()
# Unknown, empty and intentionally empty events; replaying an instance.
for i, event in enumerate(['minecraft:not.a.sound', 'minecraft:intentionally_empty', 'minecraft:empty', 'minecraft:entity.generic.eat']):
s.play(f'x{i}', event, 6, seed=50 + i)
s.add('replay', 'x3')
s.tick(25)
s.reset()
# Channel pools.
for i in range(252):
s.play('p', stone, 4, 1.0, 1.0, (float(i), 0.0, 0.0), seed=i)
for i in range(10):
s.play('s', music, 1, linear=False, relative=1, seed=i)
s.tick(2)
s.add('stopmatch', '-', '-')
s.tick(1)
def fuzz(s, rng, steps):
names = ['f0', 'f1', 'f2', 'f3', 'f4', 'f5']
live = set()
for _ in range(steps):
op = rng.random()
name = rng.choice(names)
if op < 0.25:
kind = rng.choice(['simple', 'simple', 'simple', 'loop', 'uloop', 'usub'])
event = rng.choice(s.streams if kind != 'simple' and rng.random() < 0.5 else s.events)
at = tuple(rng.choice([0.0, rng.uniform(-200, 200)]) for _ in range(3))
s.play(name, event, rng.randrange(11), rng.choice([1.0, 0.5, 2.0, 0.0, 4.0, rng.uniform(0, 3)]), rng.choice([1.0, 0.5, 2.5, rng.uniform(0.2, 3)]),
at, int(rng.random() < 0.2), rng.choice([0, 0, 0, 3]), rng.random() < 0.7, int(rng.random() < 0.3), rng.getrandbits(63), kind)
live.add(name)
elif not live:
s.tick()
elif op < 0.32:
s.add('finish', rng.choice(sorted(live)))
elif op < 0.36:
s.add('stop', rng.choice(sorted(live)))
elif op < 0.40:
s.add('fade', rng.choice(sorted(live)), rng.choice(['in', 'out']))
elif op < 0.42:
s.add('stopmatch', rng.choice(['-', rng.choice(s.events)]), rng.choice(['-', rng.randrange(11)]))
elif op < 0.45:
s.add('volume', rng.randrange(11), h.bits(rng.choice([0.0, 1.0, 0.5, rng.random()])))
elif op < 0.48:
s.add('refresh', rng.randrange(11))
elif op < 0.51:
s.add('gain', rng.randrange(11), h.bits(rng.choice([0.0, 1.0, 0.3, 1.2])))
elif op < 0.53:
s.add('player', int(rng.random() < 0.6), int(rng.random() < 0.05))
elif op < 0.55:
s.add('replay', rng.choice(sorted(live)))
elif op < 0.56:
s.add('pause')
s.tick(rng.randrange(1, 4), paused=1)
s.add('resume')
elif op < 0.57:
s.add('forget', name)
live.discard(name)
else:
s.tick(rng.randrange(1, 6))
def fixtures():
sounds = json.loads((h.RESOURCES / 'assets/minecraft/sounds.json').read_text())
names = sorted(sounds)
streams = sorted('minecraft:' + n for n in names if any(isinstance(e, dict) and e.get('stream') for e in sounds[n].get('sounds', [])))
rng = random.Random(0x454e47494e45)
events = sorted(set(['minecraft:' + rng.choice(names) for _ in range(60)] + ['minecraft:ambient.cave', 'minecraft:block.stone.break']))
s = Script(events, streams)
scripted(s)
for _ in range(40):
s.reset()
fuzz(s, rng, 150)
return s.lines
def main():
lines = fixtures()
matched, report = h.run_harness(
'sound-engine', 'VanillaSoundEngineOracle', 'sound_engine_fixture', ''.join(l + '\n' for l in lines),
extra_sources=[h.lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSoundRig.java'],
java_args=[h.RESOURCES], rust_args=[h.RESOURCES],
scope='Real SoundEngine (OpenAL Soft null device, inline executor, silent static buffers, never-ready streams): play results, '
'AL source parameters set by play/tickInGameSound/refreshCategoryVolume (gain from calculateVolume, clamped pitch, linear '
'attenuation distance, looping, position, relative), isActive, the 20-tick minimum lifetime, channel ends, stop by instance/sound/source/all, '
'pauseAllExcept/resume, tickMusicWhenPaused, queued tickables, playDelayed and manual looping, LoopSoundInstance, '
'UnderLiquidAmbientSoundInstance and UnderLiquidSubSound ticks, subtitle notifications and ranges, and the 247/8 channel pools. '
'Not compared: decoded sample output, OpenAL panning/HRTF and distance gain inside the mixer, asset loading timing.')
print(f'{matched:,} sound engine lines match the pinned client ({len(lines):,} steps): {report}', flush=True)
if __name__ == '__main__':
main()
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Compare sound event resolution with the vanilla 26.3 client.
The oracle builds the real `SoundManager` registry from the client asset root
(`SoundManager.prepare` + `Preparations.apply`: sounds.json, `replace`,
subtitles, file validation against the listed .ogg resources, event references
weighing as much as their event) and resolves seeded `SimpleSoundInstance`s:
`getOrResolve`, `getVolume`, `getPitch`, `Sound.getAttenuationDistance`, the
stream/preload/type fields and the instance random's next draw. Horizon's
`SoundRegistry` + `SoundEngine::resolve` replay the same inputs.
"""
import json
import random
try:
from . import audio_harness as h
except ImportError:
import audio_harness as h
def fixtures():
sounds = json.loads((h.RESOURCES / 'assets/minecraft/sounds.json').read_text())
rng = random.Random(0x534f554e44)
volumes = [1.0, 0.5, 0.25, 2.0, 4.0, 0.0, 1e-3, 16.0]
pitches = [1.0, 0.5, 2.0, 0.8, 1.2, 3.0, 0.1]
lines = []
for name in sorted(sounds):
event = 'minecraft:' + name
count = len(sounds[name].get('sounds', []))
seeds = [0, 1, -1, 42] + [rng.getrandbits(64) - (1 << 63) for _ in range(max(4, 2 * count))]
for seed in seeds:
lines.append(f'{event} {seed} {h.bits(rng.choice(volumes))} {h.bits(rng.choice(pitches))}')
for event in ['minecraft:intentionally_empty', 'minecraft:empty', 'minecraft:not.a.sound', 'horizon:missing', 'block.stone.break', 'music.game']:
for seed in [0, 7, -99]:
lines.append(f'{event} {seed} {h.bits(1.0)} {h.bits(1.0)}')
return lines
def main():
lines = fixtures()
matched, report = h.run_harness(
'sound-events', 'VanillaSoundEventOracle', 'sound_event_fixture', ''.join(l + '\n' for l in lines),
java_args=[h.RESOURCES], rust_args=[h.RESOURCES],
scope='Real SoundManager.prepare/Preparations.apply over the client asset root and SimpleSoundInstance.getOrResolve/getVolume/getPitch '
'for every sounds.json event with seeded randoms (weighted choice, nested event references, MultipliedFloats volume/pitch, '
'stream/preload/attenuation fields, EMPTY and INTENTIONALLY_EMPTY sentinels, draw counts) and the full registered event list.')
print(f'{matched:,} sound event lines match the pinned client ({len(lines):,} resolutions): {report}', flush=True)
if __name__ == '__main__':
main()
+182
View File
@@ -0,0 +1,182 @@
#!/usr/bin/env python3
"""Compare spawn placement checks and spawn predicates with vanilla.
Java (VanillaSpawnRulesOracle) runs SpawnPlacements.isSpawnPositionOk and
checkSpawnRules on a stand-in ServerLevel holding one column of blocks with
uniform light; Rust (spawn_rules_fixture) runs horizon_client::mobs::spawn_rules
on the same column. Every mob type is tried on surfaces, caves, water, lava,
the nether and the end, dangerous blocks, light levels, thunder, difficulty,
biomes, slime chunks, nearby players and several spawn reasons; each case
also prints the next draw of its random, pinning the number of draws.
"""
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
# Living types that are not Horizon mob types or not mobs at all.
SKIPPED = {'player', 'mannequin', 'armor_stand', 'ender_dragon', 'giant', 'copper_golem'}
SCENARIOS = {
'grass-day': dict(b=dict(m1='minecraft:grass_block'), sky=15, surface=64),
'grass-night': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, surface=64),
'grass-dusk': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=7, surface=64),
'grass-thunder': dict(b=dict(m1='minecraft:grass_block'), sky=15, thunder=1, surface=64),
'grass-peaceful': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, difficulty='peaceful', surface=64),
'grass-torch': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, light=9, surface=64),
'cave-dark': dict(b=dict(m1='minecraft:stone'), sky=0, y=20, surface=80),
'cave-lit1': dict(b=dict(m1='minecraft:stone'), sky=0, light=1, y=20, surface=80),
'cave-lit8': dict(b=dict(m1='minecraft:deepslate'), sky=0, light=8, y=-20, surface=80),
'cave-lit12': dict(b=dict(m1='minecraft:stone'), sky=0, light=12, y=20, surface=80),
'cave-dim': dict(b=dict(m1='minecraft:stone'), sky=3, y=40, surface=80),
'water-surface': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=15, y=60, surface=64, biome='minecraft:ocean'),
'water-warm': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=15, y=58, surface=64, biome='minecraft:warm_ocean'),
'water-deep': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=0, y=25, surface=64, biome='minecraft:deep_ocean'),
'water-deep-lit': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=0, light=3, y=25, surface=64, biome='minecraft:lukewarm_ocean'),
'water-mid': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=15, y=45, surface=64, biome='minecraft:cold_ocean'),
'water-roofed': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water', p3='minecraft:stone'), sky=0, y=50, surface=64, biome='minecraft:ocean'),
'water-river': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:water'), sky=0, y=50, surface=64, biome='minecraft:river', darken=11),
'water-conductor': dict(b=dict(m1='minecraft:water', p0='minecraft:water', p1='minecraft:stone'), sky=15, y=60, surface=64),
'water-seagrass': dict(b=dict(m1='minecraft:sand', p0='minecraft:water', p1='minecraft:water'), sky=15, y=55, surface=64, biome='minecraft:ocean'),
'water-clay': dict(b=dict(m1='minecraft:clay', p0='minecraft:water', p1='minecraft:water'), sky=0, y=10, surface=64, biome='minecraft:lush_caves'),
'lava-nether': dict(b=dict(m1='minecraft:lava', p0='minecraft:lava', p1='minecraft:lava'), sky=0, light=15, y=31, sea=32, dim='minecraft:the_nether', biome='minecraft:basalt_deltas'),
'lava-open': dict(b=dict(m1='minecraft:lava', p0='minecraft:lava'), sky=0, light=15, y=31, sea=32, dim='minecraft:the_nether', biome='minecraft:nether_wastes'),
'nether-dark': dict(b=dict(m1='minecraft:netherrack'), sky=0, light=0, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:nether_wastes'),
'nether-lit7': dict(b=dict(m1='minecraft:netherrack'), sky=0, light=7, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:crimson_forest'),
'nether-lit8': dict(b=dict(m1='minecraft:crimson_nylium'), sky=0, light=8, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:crimson_forest'),
'nether-wart': dict(b=dict(m1='minecraft:nether_wart_block'), sky=0, light=0, y=70, sea=32, dim='minecraft:the_nether', biome='minecraft:crimson_forest'),
'nether-soul': dict(b=dict(m1='minecraft:soul_sand'), sky=0, light=3, y=40, sea=32, dim='minecraft:the_nether', biome='minecraft:soul_sand_valley'),
'nether-magma': dict(b=dict(m1='minecraft:magma_block'), sky=0, light=3, y=40, sea=32, dim='minecraft:the_nether', biome='minecraft:basalt_deltas'),
'end': dict(b=dict(m1='minecraft:end_stone'), sky=0, light=0, y=60, dim='minecraft:the_end', biome='minecraft:the_end'),
'end-lit': dict(b=dict(m1='minecraft:end_stone'), sky=0, light=14, y=60, dim='minecraft:the_end', biome='minecraft:end_highlands'),
'ice-frozen': dict(b=dict(m1='minecraft:ice'), sky=15, y=63, surface=64, biome='minecraft:frozen_ocean'),
'ice-plains': dict(b=dict(m1='minecraft:packed_ice'), sky=15, y=64, surface=64, biome='minecraft:snowy_plains'),
'snow-block': dict(b=dict(m1='minecraft:snow_block'), sky=15, darken=11, y=70, surface=70, biome='minecraft:snowy_plains'),
'snow-layer': dict(b=dict(m1='minecraft:grass_block[snowy=true]', p0='minecraft:snow'), sky=15, y=70, surface=71, biome='minecraft:snowy_taiga'),
'powder-snow-stray': dict(b=dict(m1='minecraft:snow_block', p1='minecraft:powder_snow', p2='minecraft:powder_snow'), sky=15, darken=11, y=90, surface=93, biome='minecraft:frozen_peaks'),
'sand-beach': dict(b=dict(m1='minecraft:sand'), sky=15, y=63, surface=64, biome='minecraft:beach'),
'sand-desert': dict(b=dict(m1='minecraft:sand'), sky=15, darken=11, y=70, surface=70, biome='minecraft:desert'),
'red-sand': dict(b=dict(m1='minecraft:red_sand'), sky=15, y=80, surface=80, biome='minecraft:badlands'),
'leaves-jungle': dict(b=dict(m1='minecraft:jungle_leaves'), sky=15, y=90, surface=90, biome='minecraft:jungle'),
'grass-jungle': dict(b=dict(m1='minecraft:grass_block'), sky=15, y=70, surface=70, biome='minecraft:jungle'),
'mycelium': dict(b=dict(m1='minecraft:mycelium'), sky=15, y=70, surface=70, biome='minecraft:mushroom_fields'),
'podzol': dict(b=dict(m1='minecraft:podzol'), sky=15, y=70, surface=70, biome='minecraft:old_growth_pine_taiga'),
'mud-swamp': dict(b=dict(m1='minecraft:mud'), sky=15, y=62, surface=62, biome='minecraft:mangrove_swamp'),
'stone-peaks': dict(b=dict(m1='minecraft:stone'), sky=15, y=160, surface=160, biome='minecraft:jagged_peaks'),
'coarse-savanna': dict(b=dict(m1='minecraft:coarse_dirt'), sky=15, y=70, surface=70, biome='minecraft:savanna'),
'slab-bottom': dict(b=dict(m1='minecraft:oak_slab[type=bottom]'), sky=0, y=40, surface=80),
'slab-top': dict(b=dict(m1='minecraft:oak_slab[type=top]'), sky=0, y=40, surface=80),
'glass': dict(b=dict(m1='minecraft:glass'), sky=0, y=40, surface=80),
'glowstone': dict(b=dict(m1='minecraft:glowstone'), sky=0, light=15, y=40, surface=80),
'fire': dict(b=dict(m1='minecraft:netherrack', p0='minecraft:fire'), sky=0, light=15, y=40, surface=80),
'soul-fire': dict(b=dict(m1='minecraft:soul_soil', p0='minecraft:soul_fire'), sky=0, light=10, y=40, sea=32, dim='minecraft:the_nether', biome='minecraft:soul_sand_valley'),
'wither-rose': dict(b=dict(m1='minecraft:grass_block', p0='minecraft:wither_rose'), sky=0, y=40, surface=80),
'berry-bush': dict(b=dict(m1='minecraft:grass_block', p0='minecraft:sweet_berry_bush'), sky=15, y=70, surface=70, biome='minecraft:taiga'),
'cactus': dict(b=dict(m1='minecraft:sand', p0='minecraft:cactus'), sky=0, y=70, surface=72, biome='minecraft:desert'),
'powder-snow-feet': dict(b=dict(m1='minecraft:snow_block', p0='minecraft:powder_snow'), sky=15, darken=11, y=90, surface=91, biome='minecraft:snowy_slopes'),
'campfire': dict(b=dict(m1='minecraft:stone', p0='minecraft:campfire[lit=true]'), sky=0, light=15, y=40, surface=80),
'campfire-out': dict(b=dict(m1='minecraft:stone', p0='minecraft:campfire[lit=false]'), sky=0, y=40, surface=80),
'rail': dict(b=dict(m1='minecraft:stone', p0='minecraft:rail'), sky=0, y=40, surface=80),
'redstone-torch': dict(b=dict(m1='minecraft:stone', p0='minecraft:redstone_torch'), sky=0, light=7, y=40, surface=80),
'tall-grass': dict(b=dict(m1='minecraft:grass_block', p0='minecraft:short_grass', p1='minecraft:air'), sky=15, darken=11, y=70, surface=70),
'low-ceiling': dict(b=dict(m1='minecraft:stone', p1='minecraft:stone'), sky=0, y=40, surface=80),
'swamp-surface': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, y=62, surface=63, biome='minecraft:swamp', slime=0.5),
'swamp-full-moon': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=4, y=64, surface=65, biome='minecraft:swamp', slime=0.5),
'swamp-new-moon': dict(b=dict(m1='minecraft:grass_block'), sky=15, darken=11, y=63, surface=64, biome='minecraft:swamp', slime=0.0),
'bat-cave': dict(b=dict(m1='minecraft:stone'), sky=0, y=10, surface=80),
'bat-surface': dict(b=dict(m1='minecraft:stone'), sky=0, y=79, surface=79),
}
REASONS = ['natural', 'natural', 'natural', 'chunk_generation', 'spawner', 'trial_spawner', 'reinforcement', 'patrol']
def corpus(types):
rng = random.Random(0x5350574E)
cases = []
for t in types:
n = t.split(':')[1]
for name, s in SCENARIOS.items():
for k in range(3):
kv = {k2: v for k2, v in s.items() if k2 != 'b'}
kv.setdefault('y', 64)
for key, block in s['b'].items():
kv['at' + ('-' if key[0] == 'm' else '') + key[1:]] = block
kv['reason'] = REASONS[k] if k == 0 else rng.choice(REASONS)
kv['seed'] = rng.randrange(-2**47, 2**47)
cases.append(f'{n}/{name}/{k} type={t} ' + ' '.join(f'{a}={b}' for a, b in kv.items()))
# Slime chunks: deep caves at many chunk positions and world seeds.
if n in ('slime', 'zombie'):
for k in range(600 if n == 'slime' else 60):
cases.append(f'{n}/slime-chunk/{k} type={t} at-1=minecraft:stone sky=0 y={rng.randrange(-60, 45)} '
f'x={rng.randrange(-4000, 4000)} z={rng.randrange(-4000, 4000)} wseed={rng.randrange(-2**63, 2**63)} '
f'seed={rng.randrange(-2**47, 2**47)} reason=natural surface=80')
# Nearby players (silverfish and endermite refuse to spawn next to a targetable one).
for k, player in enumerate(['1,0,1,survival', '1,0,1,creative', '4,0,4,survival', '3,1,3,adventure', '0,4.4,0,survival',
'2,2,2,spectator']):
cases.append(f'{n}/player/{k} type={t} at-1=minecraft:stone sky=0 y=20 surface=80 player={player} '
f'seed={rng.randrange(-2**47, 2**47)} reason={rng.choice(REASONS)}')
return cases
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--prepare', action='store_true')
args = parser.parse_args()
build = lab.LOCAL / 'rust-spawn-rules-parity'
build.mkdir(parents=True, exist_ok=True)
if args.prepare:
lab.prepare()
lock, jars, libraries = base.verify_artifacts()
resources = lab.LOCAL / 'horizon-client/26.3'
entity_types = json.loads((resources / 'entity-types.json').read_text())
types = sorted(t for t, v in entity_types.items() if 'attributes' in v and t.split(':')[1] not in SKIPPED)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSpawnRulesOracle.java'
sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/spawn_rules_fixture.rs',
lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs']
tested = base.source_hashes(sources)
inputs = build / 'inputs.txt'
cases = corpus(types)
inputs.write_text(''.join(line + '\n' for line in cases), encoding='utf-8')
classes = build / 'classes'
classes.mkdir(exist_ok=True)
deps = os.pathsep.join(map(str, libraries))
def run(command, name):
with (build / (name + '.log')).open('w', encoding='utf-8') as log:
base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT)
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'),
'-cp', str(jars['server']) + os.pathsep + deps, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx2G', '-cp', os.pathsep.join([str(classes), str(jars['server']), deps]),
'dev.horizonlab.parity.VanillaSpawnRulesOracle', inputs, build / 'server.txt'], 'server')
run(['cargo', 'build', '--release', '-p', 'horizon-client', '--example', 'spawn_rules_fixture'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True))
binary = Path(metadata['target_directory']) / 'release/examples/spawn_rules_fixture'
run([binary, resources, inputs, build / 'rust.txt'], 'rust')
vanilla = (build / 'server.txt').read_text().splitlines()
errors = [l for l in vanilla if ' error ' in l]
if errors:
raise SystemExit(f'oracle errors ({len(errors)}): {errors[:5]}')
rust = (build / 'rust.txt').read_text().splitlines()
bad = [(a, b) for a, b in zip(vanilla, rust) if a != b]
if bad or len(vanilla) != len(rust):
report = '\n'.join(f' vanilla {a}\n rust {b}' for a, b in bad[:40])
raise SystemExit(f'{len(bad)} of {len(vanilla)} cases differ (rust {len(rust)} lines):\n{report}')
base.ensure_sources_unchanged(sources, tested)
lab.write_json(build / 'report.json', {
'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(), 'cases': len(cases),
'types': len(types), 'scenarios': sorted(SCENARIOS), 'sources_sha256': tested,
'scope': 'SpawnPlacements.isSpawnPositionOk (placement types, isValidSpawn, isValidEmptySpawnBlock with per-type '
'dangerous blocks) and checkSpawnRules (every registered predicate, peaceful, spawn reasons) with the '
'random draw count.'})
print(f'{len(cases):,} spawn rule cases over {len(types)} entity types match vanilla')
if __name__ == '__main__':
main()
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Compare toggle sprint/sneak (and toggle attack/use) with the pinned client:
the real Options ToggleKeyMappings driven by the real static KeyMapping
functions as keyboard presses, SDL key repeats and releases, mouse buttons,
screens opening and closing over the game (releaseAll and
restoreToggleStatesOnScreenClosed), respawning (resetToggleKeys) and toggle
options changing mid-sequence, event by event."""
import json
import random
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
def op(rng, screen):
kind = rng.choice(['key', 'key', 'key', 'key', 'button', 'button', 'open', 'close', 'option', 'option', 'respawn'])
if kind == 'key':
return ['key', rng.choice([0, 1]), rng.choice([1, 1, 0, 0, -1]), screen]
if kind == 'button':
return ['button', rng.choice([2, 3]), rng.random() < 0.5, screen]
if kind == 'option':
return ['option', rng.randrange(4), rng.random() < 0.6]
return [kind]
def cases(rng):
# Every short sequence of the main events for sneak with toggle off and on.
events = [['key', 0, 1, False], ['key', 0, 0, False], ['key', 0, -1, False], ['key', 0, 1, True], ['key', 0, 0, True],
['open'], ['close'], ['respawn'], ['option', 0, True], ['option', 0, False]]
for a in events:
for b in events:
for c in events:
for toggled in (False, True):
yield dict(ops=[['option', 0, toggled], a, b, c, ['key', 0, 1, False], ['open'], ['close']])
for _ in range(6000):
screen = False
ops = [['option', i, rng.random() < 0.5] for i in range(4)]
for _ in range(rng.randrange(1, 60)):
o = op(rng, screen)
if o[0] == 'open':
screen = True
elif o[0] == 'close':
screen = False
elif o[0] in ('key', 'button'):
o[3] = screen
ops.append(o)
yield dict(ops=ops)
def make_cases(build):
path = build / 'cases.jsonl'
count = 0
with path.open('w') as out:
for case in cases(random.Random(0x544f474c)):
out.write(json.dumps(case, separators=(',', ':')) + '\n')
count += 1
return path, count
def main():
scope = ('The real Options keyShift/keySprint/keyAttack/keyUse ToggleKeyMappings with their real toggle options and '
'shouldRestore flags, driven through the real static KeyMapping.set/click (every mapping bound to the key), '
'releaseAll, restoreToggleStatesOnScreenClosed and resetToggleKeys, dispatched as KeyboardHandler.keyPress '
'(release always; press and SDL repeat only without a screen), MouseHandler.onButton (only without a screen), '
'Gui.setScreen and LocalPlayer.respawn call them. Compares down state and pending clicks after every event. '
'The screen-consumed keyPressed/keyReleased branches and KeyMapping.setAll (an InputQuirks platform quirk) are '
'not exercised; KeyboardInput then reads isDown as the sprint and local input harnesses compare.')
harness.differential(
'rust-toggle-keys-parity', 'VanillaToggleKeysOracle', 'toggle_keys_probe', make_cases, scope,
sources=[lab.ROOT / 'crates/horizon-client/src/keymapping.rs'])
if __name__ == '__main__':
main()
+163
View File
@@ -0,0 +1,163 @@
#!/usr/bin/env python3
"""Launch the vanilla 26.3 client offline (no Microsoft account, no auth
servers: --offlineDeveloperMode) and optionally join a server straight away
(--quickPlayMultiplayer). Meant to run on a virtual screen:
vscreen start python3 tools/vanilla_client.py --name Guest --join localhost:25565
Sound goes to OpenAL's null backend. The game directory gets an options.txt
that skips the first-run screens, keeps the game running unfocused and
renders few chunks, so a harness can drive it with vscreen keys.
"""
import argparse
import hashlib
import json
import os
import subprocess
import sys
import uuid
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
GAME = ROOT / ".local/minecraft/26.3"
OPTIONS = {
"onboardAccessibility": "false",
"skipMultiplayerWarning": "true",
"joinedFirstServer": "true",
"tutorialStep": "none",
"pauseOnLostFocus": "false",
"renderDistance": "6",
"simulationDistance": "6",
"maxFps": "30",
"narrator": "0",
"soundCategory_master": "0.0",
"realmsNotifications": "false",
"hideServerAddress": "false",
"autoJump": "false",
"chatLinksPrompt": "false",
"onlyShowSecureChat": "false",
"rawMouseInput": "false",
}
def offline_uuid(name):
digest = bytearray(hashlib.md5(("OfflinePlayer:" + name).encode()).digest())
digest[6] = (digest[6] & 0x0F) | 0x30
digest[8] = (digest[8] & 0x3F) | 0x80
return uuid.UUID(bytes=bytes(digest))
def linux_library(path):
name = Path(path).name
if "natives-" in name:
return name.endswith("natives-linux.jar")
if "netty-transport-native" in name and ("osx" in name or "aarch_64" in name):
return False
return "java-objc-bridge" not in name
def classpath():
prepared = json.loads((GAME / "prepared.json").read_text())
jars = [ROOT / p for p in prepared["libraries"]["client"] if linux_library(p)]
return [GAME / "jars/client.jar", *jars]
def extract_natives(jars, target):
target.mkdir(parents=True, exist_ok=True)
for jar in jars:
if not jar.name.endswith("natives-linux.jar"):
continue
with zipfile.ZipFile(jar) as archive:
for name in archive.namelist():
if name.endswith(".so") and "arm" not in name and "aarch" not in name:
out = target / Path(name).name
if not out.exists():
out.write_bytes(archive.read(name))
def write_options(game_dir, extra):
path = game_dir / "options.txt"
current = {}
if path.exists():
for line in path.read_text().splitlines():
if ":" in line:
k, v = line.split(":", 1)
current[k] = v
current.update(OPTIONS)
current.update(extra)
path.write_text("".join(f"{k}:{v}\n" for k, v in current.items()))
def environment():
env = dict(os.environ)
libs = [p for p in (os.environ.get("NIX_LD_LIBRARY_PATH", ""), "/run/opengl-driver/lib",
"/run/current-system/sw/share/nix-ld/lib") if p]
env["LD_LIBRARY_PATH"] = ":".join(libs + [env.get("LD_LIBRARY_PATH", "")]).strip(":")
env["ALSOFT_DRIVERS"] = "null"
return env
def command(args):
jars = classpath()
natives = args.game_dir / "natives"
extract_natives(jars, natives)
assets = args.assets or (args.game_dir / "assets")
(assets / "indexes").mkdir(parents=True, exist_ok=True)
cmd = ["java", f"-Xmx{args.heap}", "-XX:StackShadowPages=32",
"--enable-native-access=ALL-UNNAMED",
"--add-exports", "java.base/jdk.internal.misc=ALL-UNNAMED",
f"-Djava.library.path={natives}", f"-Dorg.lwjgl.system.SharedLibraryExtractPath={natives}",
f"-Dio.netty.native.workdir={natives}",
"-cp", os.pathsep.join(map(str, jars)), "net.minecraft.client.main.Main",
"--username", args.name, "--uuid", offline_uuid(args.name).hex,
"--accessToken", "0", "--offlineDeveloperMode",
"--version", "26.3", "--gameDir", str(args.game_dir),
"--assetsDir", str(assets), "--assetIndex", "34",
"--width", str(args.width), "--height", str(args.height)]
if args.join:
cmd += ["--quickPlayMultiplayer", args.join]
if args.world:
cmd += ["--quickPlaySingleplayer", args.world]
if args.lan_port is not None:
# The vanilla client as reference LAN host (OfflineLanHost).
cp = cmd.index("-cp") + 1
cmd[cp] = os.pathsep.join([str(args.classes), cmd[cp]])
main = cmd.index("net.minecraft.client.main.Main")
cmd[main:main + 1] = [f"-Dhorizon.lanPort={args.lan_port}", "dev.horizonlab.parity.OfflineLanHost"]
if args.backend:
cmd += ["--graphicsBackend", args.backend]
return cmd
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--name", default="Guest")
parser.add_argument("--join", help="HOST:PORT to join on start")
parser.add_argument("--world", help="open this saves/ folder in singleplayer on start")
parser.add_argument("--game-dir", type=Path, default=ROOT / ".local/vanilla-client")
parser.add_argument("--assets", type=Path)
parser.add_argument("--heap", default="3G")
parser.add_argument("--width", type=int, default=1280)
parser.add_argument("--height", type=int, default=800)
parser.add_argument("--lan-port", type=int,
help="open the --world to LAN on this port without authentication (needs --classes)")
parser.add_argument("--classes", type=Path, default=ROOT / ".local/mp/oracle",
help="compiled OfflineLanHost (mods/horizon/src/test/java)")
parser.add_argument("--backend", help="graphics backend (opengl or vulkan)")
parser.add_argument("--option", action="append", default=[], help="KEY:VALUE for options.txt")
parser.add_argument("--print", action="store_true", help="print the command and exit")
args = parser.parse_args()
args.game_dir = args.game_dir.resolve()
args.game_dir.mkdir(parents=True, exist_ok=True)
write_options(args.game_dir, dict(o.split(":", 1) for o in args.option))
cmd = command(args)
if args.print:
print(" ".join(cmd))
return
sys.exit(subprocess.run(cmd, cwd=args.game_dir, env=environment()).returncode)
if __name__ == "__main__":
main()