#!/usr/bin/env python3 """Compare LOD0-2 owner mesh edge crossings before and after L109.""" from __future__ import annotations import json import math import statistics import struct import subprocess import time from pathlib import Path ROOT = Path(__file__).resolve().parents[4] OUT = ROOT / "Saved/Linux/l109/crossings" DATA = ROOT / "Standalone/data/owner_world.json" BINARIES = { "before": ROOT / "Saved/Linux/l109/bin-baseline/VoxelForgeCoreHeadless-l109-baseline", "after": ROOT / "Saved/Linux/l109/bin-final/VoxelForgeCoreHeadless-l109-clang", } CAMERAS = { "SW": (8.0, 16.0, -372.2626953125), "FI": (25.8369140625, 3.19921875, -737.0), "TN": (19.166015625, -14.2001953125, -753.3740234375), "VS": (-20.0625, -5.068359375, -900.353515625), } def read_exact(stream, size): data = stream.read(size) if len(data) != size: raise RuntimeError("truncated VFMSH export") return data def crossing_map(path: Path) -> tuple[dict, dict]: crossings = {} meta = {"tiles": 0, "surface_vertices": 0, "classified": 0} with path.open("rb") as stream: magic = read_exact(stream, 8) materials = magic == b"VFMSH002" if magic not in (b"VFMSH001", b"VFMSH002"): raise RuntimeError(f"invalid mesh export {path}") version, voxel_um, tile_count = struct.unpack("<3I", read_exact(stream, 12)) if version != (2 if materials else 1): raise RuntimeError("VFMSH version mismatch") read_exact(stream, 40) voxel_m = voxel_um / 1_000_000.0 for _ in range(tile_count): key = struct.unpack("<4i", read_exact(stream, 16)) surface_count, _skirts, vertex_count, index_count, mask_count = struct.unpack( "<5I", read_exact(stream, 20)) positions = struct.iter_unpack("<3f", read_exact(stream, vertex_count * 12)) values = list(positions) read_exact(stream, vertex_count * 12) # normals if materials: read_exact(stream, vertex_count * 10) read_exact(stream, index_count * 4 + mask_count) meta["tiles"] += 1 meta["surface_vertices"] += min(surface_count, vertex_count) unit = voxel_m * (1 << key[3]) for position in values[:min(surface_count, vertex_count)]: grid = tuple(value / unit for value in position) fractions = tuple(abs(value - round(value)) for value in grid) axis = max(range(3), key=fractions.__getitem__) if fractions[axis] < 1.0e-4: continue fixed = [index for index in range(3) if index != axis] if any(fractions[index] > 0.01 for index in fixed): continue edge = [0, 0, 0] for index in fixed: edge[index] = int(round(grid[index])) edge[axis] = math.floor(grid[axis]) identity = (key[3], axis, *edge) crossings.setdefault(identity, tuple(float(v) for v in position)) meta["classified"] += 1 if stream.read(1): raise RuntimeError("trailing data in mesh export") meta["classified_pct"] = (100.0 * meta["classified"] / meta["surface_vertices"] if meta["surface_vertices"] else 0.0) return crossings, meta def export(strate: str, variant: str) -> Path: OUT.mkdir(parents=True, exist_ok=True) mesh = OUT / f"{strate.lower()}-{variant}.vfmesh" log = OUT / f"{strate.lower()}-{variant}.log" camera = ",".join(f"{v:.12f}" for v in CAMERAS[strate]) + ",0,0" command = [ "taskset", "-c", "0-11", "prlimit", "--as=6442450944", "--", "timeout", "1740s", str(BINARIES[variant]), str(DATA), "--world-assembler-prototype", "--stream-benchmark", "--stream-pipeline", "--workers=8", "--clip-radius=3", "--max-clip-level=2", "--max-level=2", "--force-generate", "--recipe=surface-world", f"--camera={camera}", "--render-distance-chunks=0", f"--mesh-export={mesh}", ] started = time.monotonic() with log.open("w", encoding="utf-8") as stream: result = subprocess.run(command, cwd=ROOT, stdout=stream, stderr=subprocess.STDOUT, timeout=1740, check=False) output = log.read_text(encoding="utf-8", errors="replace") if result.returncode or not mesh.is_file() or "status=PASS" not in output: raise RuntimeError(f"mesh export failed: {strate}/{variant} exit={result.returncode} {log}") return mesh def main() -> int: summaries = [] for strate in CAMERAS: paths = {variant: export(strate, variant) for variant in ("before", "after")} maps = {variant: crossing_map(path) for variant, path in paths.items()} old, old_meta = maps["before"] new, new_meta = maps["after"] old_keys, new_keys = set(old), set(new) shared = old_keys & new_keys moved_cm = [100.0 * math.dist(old[key], new[key]) for key in shared if math.dist(old[key], new[key]) > 0.0001] row = { "strate": strate, "scope": "camera LOD0-2 mesh window; global lattice edge IDs", "added_crossings": len(new_keys - old_keys), "removed_crossings": len(old_keys - new_keys), "shared_crossings": len(shared), "moved_crossings": len(moved_cm), "mean_moved_cm": statistics.mean(moved_cm) if moved_cm else 0.0, "max_moved_cm": max(moved_cm, default=0.0), "before": old_meta, "after": new_meta, "classified_pair_coverage_pct": min(old_meta["classified_pct"], new_meta["classified_pct"]), "exports": {key: str(value.relative_to(ROOT)) for key, value in paths.items()}, } summaries.append(row) print("[L109CrossingDelta] " + json.dumps(row, sort_keys=True), flush=True) (OUT / "summary.json").write_text( json.dumps({"measurement": "per-vertex marching-cubes edge classifier; compare shared global lattice edges; positions >0.01cm count as moved", "strata": summaries}, indent=2) + "\n", encoding="utf-8") return 0 if __name__ == "__main__": raise SystemExit(main())