diff options
| author | Kacper Serewiś <kacper@serewis.nl> | 2026-11-23 16:37:15 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-23 09:37:15 -0600 |
| commit | c1aa89e0ffa89b88ca3e7dafb77bc87e71eb9ff2 (patch) | |
| tree | 21b6ca180c5c7963865e1d42d7f752e1acab0d5c | |
| parent | 01f8116d1b58f7fe632ac92a9a51bdd990a8fecc (diff) | |
BUILD-2389: verify keyed drawable offset predictions against exported models (#6900)
Squash-merged after diff review of PR #6900 - BUILD-2389: verify keyed drawable offset predictions against exported models
| -rw-r--r-- | docs/models.md | 29 | ||||
| -rw-r--r-- | tests/test_world_drawable_lookup.py | 43 | ||||
| -rw-r--r-- | tests/test_world_drawable_verify.py | 60 | ||||
| -rw-r--r-- | tools/world_drawable_lookup.py | 100 | ||||
| -rw-r--r-- | tools/world_drawable_verify.py | 109 |
5 files changed, 341 insertions, 0 deletions
diff --git a/docs/models.md b/docs/models.md index fd783dd36..5c29b2332 100644 --- a/docs/models.md +++ b/docs/models.md | |||
| @@ -829,3 +829,32 @@ geometry from the BIN chunk. Standard library only; no game files. | |||
| 829 | `levels.rpf` has the same 343,327 rows in a full export (50,731 fragments, 2,509,947,536 | 829 | `levels.rpf` has the same 343,327 rows in a full export (50,731 fragments, 2,509,947,536 |
| 830 | triangles). | 830 | triangles). |
| 831 | 4. Keep the README and issue #29 in sync with the new counts. | 831 | 4. Keep the README and issue #29 in sync with the new counts. |
| 832 | |||
| 833 | ### Predict model offsets for placements | ||
| 834 | |||
| 835 | Run `python -I tools/world_drawable_lookup.py entities.jsonl archetypes.json names.json` | ||
| 836 | with the placement rows from `world_index.py --entities-out`, the definitions from | ||
| 837 | `world_archetypes.py`, and a bounded `rpf9_names.py --types dr,ft` report. The command | ||
| 838 | prints local scratch JSON. Supply `--manifest path/to/models/manifest.json` for each | ||
| 839 | existing export whose listed identities should be excluded. | ||
| 840 | |||
| 841 | The lookup requires agreement between the placement archetype, the definition's name and | ||
| 842 | assetName, the resource stem's joaat and its 64-bit placement key. It considers type 1 | ||
| 843 | fragments and type 2 drawables at page offset +16. Multiple offsets for an identity in | ||
| 844 | the indexed window are marked ambiguous. Even a single hit is a prediction: a stream | ||
| 845 | can mention another model. Export a window around the predicted offset with | ||
| 846 | `rpf9dump models <archive> <outdir> --start BYTES --length BYTES`, compare the manifest offset and | ||
| 847 | model identity and run `world_build.py --placements` with the exported geometry. | ||
| 848 | |||
| 849 | Save the lookup JSON and run | ||
| 850 | `python -I tools/world_drawable_verify.py lookup.json first/models/manifest.json second/models/manifest.json` | ||
| 851 | to verify single-offset predictions. Supply completed normal model manifests from the | ||
| 852 | same source archive. The verifier reads cached JSON only. It uses the world builder's | ||
| 853 | name hashes and counts each identity and its placements once. A matching offset and both | ||
| 854 | hashes confirm an observation, including dictionary children sharing an offset. The local | ||
| 855 | report counts repeat exact observations and lists other offsets for the same identity. | ||
| 856 | Without an exact match, a different name at the offset takes precedence over a matching | ||
| 857 | identity elsewhere. The coverage flag independently records whether the predicted offset | ||
| 858 | falls in a supplied scan (start inclusive, end exclusive). A full scan covers all offsets. | ||
| 859 | A covered prediction with no named evidence remains missing. Geometry loadability is | ||
| 860 | checked separately by running the normal world builder on confirmed placement rows. | ||
diff --git a/tests/test_world_drawable_lookup.py b/tests/test_world_drawable_lookup.py new file mode 100644 index 000000000..fa4558257 --- /dev/null +++ b/tests/test_world_drawable_lookup.py | |||
| @@ -0,0 +1,43 @@ | |||
| 1 | """Synthetic coverage of the report join and its ambiguous/missing evidence.""" | ||
| 2 | import json | ||
| 3 | from pathlib import Path | ||
| 4 | import sys | ||
| 5 | import tempfile | ||
| 6 | import unittest | ||
| 7 | |||
| 8 | sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) | ||
| 9 | import world_drawable_lookup as lookup | ||
| 10 | import world_names | ||
| 11 | |||
| 12 | |||
| 13 | class DrawableLookupTest(unittest.TestCase): | ||
| 14 | def test_only_export_candidates_with_consistent_evidence(self): | ||
| 15 | with tempfile.TemporaryDirectory() as tmp: | ||
| 16 | root = Path(tmp) | ||
| 17 | names = ["one", "many", "conflict", "wrong_key", "unaligned", "cached", "missing_key"] | ||
| 18 | definitions, streams, placements = [], [], [] | ||
| 19 | for i, name in enumerate(names): | ||
| 20 | h = world_names.joaat(name) | ||
| 21 | definitions.append({"name": h, "asset_name": h, "asset_type": 2}) | ||
| 22 | key = world_names.hash64(name) | ||
| 23 | placements.append({"archetype": f"{h:x}", "key": f"{key:x}", "position": [0, 0, 0], | ||
| 24 | "rotation": [0, 0, 0, 1], "lod_level": 6}) | ||
| 25 | streams.append({"offset": 4096 * i + 16, "names": [name + ".#dr"]}) | ||
| 26 | streams.append({"offset": 4096 * 8 + 16, "names": ["many.#dr"]}) | ||
| 27 | definitions.append(dict(definitions[2], asset_type=1)) | ||
| 28 | placements[3]["key"] = "0" | ||
| 29 | streams[4]["offset"] += 1 | ||
| 30 | placements[-1].pop("key") | ||
| 31 | for file, data in [("defs", {"archetypes": definitions}), | ||
| 32 | ("names", {"summary": {"archive": "test.rpf"}, "files": streams}), | ||
| 33 | ("manifest", {"Items": [{"Name": "cached"}]})]: | ||
| 34 | (root / file).write_text(json.dumps(data), encoding="utf-8", newline="\n") | ||
| 35 | (root / "entities").write_text("\n".join(map(json.dumps, placements)), encoding="utf-8", newline="\n") | ||
| 36 | result = lookup.lookup(root / "entities", root / "defs", root / "names", [root / "manifest"]) | ||
| 37 | self.assertEqual(result["outcomes"], {"candidate": 1, "ambiguous": 1, "unresolved": 3, | ||
| 38 | "listed_in_manifest": 1, "missing_or_invalid_key": 1}) | ||
| 39 | self.assertEqual(sorted(r["offsets"] for r in result["candidates"]), [[16], [4112, 32784]]) | ||
| 40 | |||
| 41 | |||
| 42 | if __name__ == "__main__": | ||
| 43 | unittest.main() | ||
diff --git a/tests/test_world_drawable_verify.py b/tests/test_world_drawable_verify.py new file mode 100644 index 000000000..af5882d04 --- /dev/null +++ b/tests/test_world_drawable_verify.py | |||
| @@ -0,0 +1,60 @@ | |||
| 1 | """Synthetic export windows and keyed model observations.""" | ||
| 2 | import json | ||
| 3 | from pathlib import Path | ||
| 4 | import sys | ||
| 5 | import tempfile | ||
| 6 | import unittest | ||
| 7 | |||
| 8 | sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) | ||
| 9 | import world_drawable_verify as verifier | ||
| 10 | import world_names | ||
| 11 | |||
| 12 | |||
| 13 | class VerifyTest(unittest.TestCase): | ||
| 14 | def setUp(self): | ||
| 15 | tmp = tempfile.TemporaryDirectory() | ||
| 16 | self.addCleanup(tmp.cleanup) | ||
| 17 | self.root = Path(tmp.name) | ||
| 18 | |||
| 19 | def write(self, name, data): | ||
| 20 | path = self.root / name | ||
| 21 | path.write_text(json.dumps(data), encoding="utf-8", newline="\n") | ||
| 22 | return path | ||
| 23 | |||
| 24 | def test_join_counts_and_window_edges(self): | ||
| 25 | candidates = [] | ||
| 26 | for name, offset in [("one", 10), ("two", 12), ("three", 13), ("four", 14), ("five", 20)]: | ||
| 27 | candidates.append({"archetype": format(world_names.joaat(name), "x"), | ||
| 28 | "key": format(world_names.hash64(name), "x"), "offsets": [offset], | ||
| 29 | "status": "candidate", "placements": 3}) | ||
| 30 | # A 32-bit match alone cannot confirm the prediction. | ||
| 31 | candidates[1]["archetype"] = candidates[0]["archetype"] | ||
| 32 | candidates.append(dict(candidates[0], status="ambiguous", offsets=[10, 15])) | ||
| 33 | predictions = self.write("lookup", {"archive": "source.rpf", "candidates": candidates}) | ||
| 34 | export = {"src": "source.rpf", "Scan": {"Start": 10, "Length": 10}, | ||
| 35 | "Items": [{"Name": "one.#dr", "Offset": 10}, {"Name": "one", "Offset": 12}, | ||
| 36 | {"Name": "three", "Offset": 18}, {"Name": "", "Offset": 14}]} | ||
| 37 | first = self.write("first", export) | ||
| 38 | second = self.write("second", dict(export, Items=export["Items"][:1])) | ||
| 39 | result = verifier.verify(predictions, [first, second, first]) | ||
| 40 | self.assertEqual([r["status"] for r in result["rows"]], | ||
| 41 | ["confirmed", "conflicting_name", "conflicting_offset", "missing_evidence", | ||
| 42 | "outside_windows"]) | ||
| 43 | self.assertEqual(result["placements"], {s: 3 for s in result["identities"]}) | ||
| 44 | self.assertEqual(result["rows"][0]["duplicate_observations"], 1) | ||
| 45 | self.assertEqual(result["rows"][0]["other_identity_offsets"], [12]) | ||
| 46 | full = self.write("full", dict(export, Scan={})) | ||
| 47 | self.assertEqual(verifier.verify(predictions, [full])["identities"]["missing_evidence"], 2) | ||
| 48 | |||
| 49 | def test_reject_unrelated_archive_and_bad_bounds(self): | ||
| 50 | predictions = self.write("lookup", {"archive": "source.rpf", "candidates": []}) | ||
| 51 | for source, scan in [("elsewhere/source.rpf", {}), ("source.rpf", {"Start": 0}), | ||
| 52 | ("source.rpf", {"Start": True, "Length": 5}), | ||
| 53 | ("source.rpf", {"Start": 0, "Length": 2})]: | ||
| 54 | manifest = self.write("manifest", {"src": source, "Scan": scan, "Items": [{"Offset": 2}]}) | ||
| 55 | with self.subTest(source=source, scan=scan), self.assertRaises(ValueError): | ||
| 56 | verifier.verify(predictions, [manifest]) | ||
| 57 | |||
| 58 | |||
| 59 | if __name__ == "__main__": | ||
| 60 | unittest.main() | ||
diff --git a/tools/world_drawable_lookup.py b/tools/world_drawable_lookup.py new file mode 100644 index 000000000..0d25d9e19 --- /dev/null +++ b/tools/world_drawable_lookup.py | |||
| @@ -0,0 +1,100 @@ | |||
| 1 | """Predict model export offsets from local world_archetypes and rpf9_names reports.""" | ||
| 2 | import argparse | ||
| 3 | from collections import Counter, defaultdict | ||
| 4 | import json | ||
| 5 | import os | ||
| 6 | import sys | ||
| 7 | |||
| 8 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | ||
| 9 | import world_build | ||
| 10 | import world_names | ||
| 11 | |||
| 12 | |||
| 13 | def report_rows(path, field): | ||
| 14 | with open(path, encoding="utf-8-sig") as handle: | ||
| 15 | report = json.load(handle) | ||
| 16 | if not isinstance(report, dict) or not isinstance(report.get(field), list): | ||
| 17 | raise ValueError(f"{path}: expected a {field} array") | ||
| 18 | if any(not isinstance(row, dict) for row in report[field]): | ||
| 19 | raise ValueError(f"{path}: non-object in {field}") | ||
| 20 | return report | ||
| 21 | |||
| 22 | |||
| 23 | def lookup(placements, archetypes, names, manifests): | ||
| 24 | definitions = defaultdict(set) | ||
| 25 | for row in report_rows(archetypes, "archetypes")["archetypes"]: | ||
| 26 | definitions[row.get("name")].add((row.get("asset_name"), row.get("asset_type"))) | ||
| 27 | |||
| 28 | counts = world_build._placement_counts() | ||
| 29 | wanted = Counter() | ||
| 30 | outcomes = Counter() | ||
| 31 | for row in world_build.iter_placements(placements, counts, world_build.ALL_LOD_LEVELS): | ||
| 32 | try: | ||
| 33 | key = int(row.get("key"), 16) | ||
| 34 | except (TypeError, ValueError): | ||
| 35 | outcomes["missing_or_invalid_key"] += 1 | ||
| 36 | continue | ||
| 37 | wanted[row["_arch"], key] += 1 | ||
| 38 | |||
| 39 | listed = set() | ||
| 40 | for path in manifests: | ||
| 41 | entries = report_rows(path, "Items")["Items"] | ||
| 42 | index = world_build.model_name_index([("", item) for item in entries], world_names) | ||
| 43 | listed.update((h, key) for h, items in index.items() for _, _, key in items) | ||
| 44 | |||
| 45 | offsets = defaultdict(set) | ||
| 46 | index = report_rows(names, "files") | ||
| 47 | summary = index.get("summary") | ||
| 48 | archive = summary.get("archive") if isinstance(summary, dict) else None | ||
| 49 | if not isinstance(archive, str) or not archive: | ||
| 50 | raise ValueError(f"{names}: missing archive in summary") | ||
| 51 | for row in index["files"]: | ||
| 52 | offset = row.get("offset") | ||
| 53 | if type(offset) is not int or offset < 0 or not isinstance(row.get("names"), list): | ||
| 54 | raise ValueError(f"{names}: invalid resource name index row") | ||
| 55 | if offset % 4096 != 16: | ||
| 56 | continue | ||
| 57 | for name in row["names"]: | ||
| 58 | if not isinstance(name, str): | ||
| 59 | raise ValueError(f"{names}: expected a resource name string") | ||
| 60 | stem, _, suffix = name.rpartition(".#") | ||
| 61 | asset_type = {"ft": 1, "dr": 2}.get(suffix.lower()) | ||
| 62 | if not stem or asset_type is None: | ||
| 63 | continue | ||
| 64 | h = world_names.joaat(stem) | ||
| 65 | identity = h, world_names.hash64(stem) | ||
| 66 | if identity in wanted and definitions.get(h) == {(h, asset_type)}: | ||
| 67 | offsets[identity].add(offset) | ||
| 68 | |||
| 69 | candidates = [] | ||
| 70 | for identity, n in sorted(wanted.items()): | ||
| 71 | h, key = identity | ||
| 72 | hits = sorted(offsets.get(identity, ())) | ||
| 73 | if identity in listed: | ||
| 74 | outcomes["listed_in_manifest"] += n | ||
| 75 | elif hits: | ||
| 76 | status = "candidate" if len(hits) == 1 else "ambiguous" | ||
| 77 | outcomes[status] += n | ||
| 78 | candidates.append({"archetype": f"{h:08x}", "key": f"{key:016x}", "offsets": hits, | ||
| 79 | "placements": n, "status": status}) | ||
| 80 | else: | ||
| 81 | outcomes["unresolved"] += n | ||
| 82 | return {"archive": archive, "placements": counts, "outcomes": outcomes, "candidates": candidates} | ||
| 83 | |||
| 84 | |||
| 85 | def main(): | ||
| 86 | parser = argparse.ArgumentParser(description=__doc__) | ||
| 87 | parser.add_argument("placements", help="world_index entity JSONL") | ||
| 88 | parser.add_argument("archetypes", help="world_archetypes JSON") | ||
| 89 | parser.add_argument("names", help="rpf9_names JSON for the source archive") | ||
| 90 | parser.add_argument("--manifest", action="append", default=[], help="exclude identities already listed (repeatable)") | ||
| 91 | args = parser.parse_args() | ||
| 92 | try: | ||
| 93 | result = lookup(args.placements, args.archetypes, args.names, args.manifest) | ||
| 94 | except (OSError, ValueError, TypeError) as exc: | ||
| 95 | parser.exit(1, f"{parser.prog}: {exc}\n") | ||
| 96 | print(json.dumps(result, indent=1)) | ||
| 97 | |||
| 98 | |||
| 99 | if __name__ == "__main__": | ||
| 100 | main() | ||
diff --git a/tools/world_drawable_verify.py b/tools/world_drawable_verify.py new file mode 100644 index 000000000..2addfd274 --- /dev/null +++ b/tools/world_drawable_verify.py | |||
| @@ -0,0 +1,109 @@ | |||
| 1 | """Verify single-offset world_drawable_lookup predictions against normal model exports.""" | ||
| 2 | import argparse | ||
| 3 | from collections import Counter, defaultdict | ||
| 4 | import json | ||
| 5 | import os | ||
| 6 | import sys | ||
| 7 | |||
| 8 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | ||
| 9 | from world_drawable_lookup import report_rows | ||
| 10 | import world_build | ||
| 11 | import world_names | ||
| 12 | |||
| 13 | |||
| 14 | def archive_path(value): | ||
| 15 | if not isinstance(value, str) or not value.strip(): | ||
| 16 | raise ValueError("expected a source archive path") | ||
| 17 | return os.path.normcase(os.path.abspath(value)) | ||
| 18 | |||
| 19 | |||
| 20 | def verify(predictions, manifests): | ||
| 21 | report = report_rows(predictions, "candidates") | ||
| 22 | archive = archive_path(report.get("archive")) | ||
| 23 | windows = [] | ||
| 24 | full_scan = False | ||
| 25 | observations = Counter() | ||
| 26 | named_offsets = set() | ||
| 27 | by_identity = defaultdict(set) | ||
| 28 | paths = dict.fromkeys(os.path.normcase(os.path.realpath(path)) for path in manifests) | ||
| 29 | for path in paths: | ||
| 30 | export = report_rows(path, "Items") | ||
| 31 | if archive_path(export.get("src")) != archive: | ||
| 32 | raise ValueError(f"{path}: different source archive from predictions") | ||
| 33 | scan = export.get("Scan") | ||
| 34 | if not isinstance(scan, dict): | ||
| 35 | raise ValueError(f"{path}: missing Scan metadata") | ||
| 36 | bounded = "Start" in scan or "Length" in scan | ||
| 37 | if bounded: | ||
| 38 | start, length = scan.get("Start"), scan.get("Length") | ||
| 39 | if any(type(n) is not int or n < 0 for n in (start, length)): | ||
| 40 | raise ValueError(f"{path}: invalid Scan.Start or Scan.Length") | ||
| 41 | windows.append((start, start + length)) | ||
| 42 | else: | ||
| 43 | full_scan = True | ||
| 44 | for item in export["Items"]: | ||
| 45 | offset = item.get("Offset") | ||
| 46 | if type(offset) is not int or offset < 0 or (bounded and not start <= offset < start + length): | ||
| 47 | raise ValueError(f"{path}: invalid item offset for scan") | ||
| 48 | index = world_build.model_name_index([("", item) for item in export["Items"]], world_names) | ||
| 49 | for h, entries in index.items(): | ||
| 50 | for _, item, key in entries: | ||
| 51 | offset = item["Offset"] | ||
| 52 | observations[h, key, offset] += 1 | ||
| 53 | named_offsets.add(offset) | ||
| 54 | by_identity[h, key].add(offset) | ||
| 55 | |||
| 56 | identities, placements = Counter(), Counter() | ||
| 57 | rows = [] | ||
| 58 | seen = set() | ||
| 59 | for row in report["candidates"]: | ||
| 60 | if row.get("status") == "ambiguous": | ||
| 61 | continue | ||
| 62 | offsets = row.get("offsets") | ||
| 63 | if (row.get("status") != "candidate" or not isinstance(offsets, list) or len(offsets) != 1 | ||
| 64 | or type(offsets[0]) is not int or offsets[0] < 0): | ||
| 65 | raise ValueError("expected single-offset candidate") | ||
| 66 | offset = offsets[0] | ||
| 67 | h, key = int(row["archetype"], 16), int(row["key"], 16) | ||
| 68 | if (h, key) in seen: | ||
| 69 | raise ValueError("duplicate candidate identity") | ||
| 70 | seen.add((h, key)) | ||
| 71 | n = row["placements"] | ||
| 72 | if type(n) is not int or n < 1: | ||
| 73 | raise ValueError("expected positive placement count") | ||
| 74 | covered = full_scan or any(start <= offset < end for start, end in windows) | ||
| 75 | exact = observations[h, key, offset] | ||
| 76 | elsewhere = sorted(by_identity[h, key] - {offset}) | ||
| 77 | if exact: | ||
| 78 | status = "confirmed" | ||
| 79 | elif offset in named_offsets: | ||
| 80 | status = "conflicting_name" | ||
| 81 | elif elsewhere: | ||
| 82 | status = "conflicting_offset" | ||
| 83 | elif covered: | ||
| 84 | status = "missing_evidence" | ||
| 85 | else: | ||
| 86 | status = "outside_windows" | ||
| 87 | identities[status] += 1 | ||
| 88 | placements[status] += n | ||
| 89 | rows.append({"archetype": row["archetype"], "key": row["key"], "offset": offset, | ||
| 90 | "placements": n, "status": status, "covered": covered, | ||
| 91 | "exact_observations": exact, "duplicate_observations": max(0, exact - 1), | ||
| 92 | "other_identity_offsets": elsewhere}) | ||
| 93 | return {"identities": identities, "placements": placements, "rows": rows} | ||
| 94 | |||
| 95 | |||
| 96 | def main(): | ||
| 97 | parser = argparse.ArgumentParser(description=__doc__) | ||
| 98 | parser.add_argument("predictions", help="local world_drawable_lookup JSON") | ||
| 99 | parser.add_argument("manifest", nargs="+", help="rpf9dump models manifest.json from the same archive") | ||
| 100 | args = parser.parse_args() | ||
| 101 | try: | ||
| 102 | result = verify(args.predictions, args.manifest) | ||
| 103 | except (KeyError, OSError, TypeError, ValueError) as exc: | ||
| 104 | parser.exit(1, f"{parser.prog}: {exc}\n") | ||
| 105 | print(json.dumps(result, indent=1)) | ||
| 106 | |||
| 107 | |||
| 108 | if __name__ == "__main__": | ||
| 109 | main() | ||