bvh_match: leave out geometries by render bucket, not a shader-hash list (ASSET-349) (#6330)

Squash-merged after review of PR #6330 - bvh_match: leave out geometries by render bucket (ASSET-349)
This commit is contained in:
Codimation
2026-11-23 06:16:56 -08:00
committed by GitHub
parent b54dbd6a80
commit 4beffda88a
3 changed files with 160 additions and 28 deletions

View File

@ -499,7 +499,8 @@ the 10 samples, of its second LOD for most of the interior's other BLAS (below).
is left out exactly when its shader is one of a set of shaders: the 65 geometries left out use 7 shader hashes, the
67 kept use 8 others, and no hash is in both. Two of the 7 cover 54 of the 65; the other five occur only in the two
drawables that hold decals and baked room dressing. (On the 8 samples identified first, the skipped geometries were
read as using only two shaders; the decals drawable among them skips geometries of all 7.) The hashes stay out of
read as using only two shaders; the decals drawable among them skips geometries of all 7.) The 7 hashes are not the
rule: the material's render bucket is (ASSET-349, "Which geometries the BVH leaves out" below). The hashes stay out of
this repository (§8). They are the shader-group
hashes (first word of the shader record; shader group at drawable `+0x10`, pointer array at group `+0x10`, `u16`
count at `+0x18`, shader index per geometry in the model's `u16` array at `+0x20`) that only skipped geometries
@ -509,6 +510,42 @@ then one contiguous stream of 8-byte records; the other vertex attributes follow
per vertex of the whole block are not a position stride. The leaves address triangles in primitive order of the
meshlet index buffer.
**Which geometries the BVH leaves out (ASSET-349, measured; one rule with known exceptions).** The choice follows the
render bucket of the geometry's material: the byte at `+57` of the shader record, with the bucket mask at `+60`
(`third_party/rpf9-explorer/Core/RageModelDecoder.cs:680`; `rpf9dump models` writes the byte as `RenderBucket`). A
geometry is kept when the low 7 bits of that byte are 0 or 3 and left out otherwise; bit 7 does not change the
choice. What the buckets mean is not measured here (in earlier RAGE games 1 and 2 are the alpha and decal buckets;
that is a hypothesis for this one).
* *The 10 samples:* 132 of 132 geometries follow it (all 65 left out are bucket 1 or 2, all 67 kept bucket 0 or 3),
and for each of the 10 the kept geometries are exactly the BLAS's signature, with one consistent drawable each
(re-run against the 3 GiB window export).
* *The whole archive:* a `rpf9dump models` export of all of `levels.rpf` (343,327 drawables, 346,785 models,
2,251,094 materials, 3,854,587 geometries; first LOD only) has bucket bytes 0-6 and 128-131: 3,091,235 geometries
kept by the rule and 763,352 left out, 70,334 models with both. Bit 7 is set on 35,339 materials.
* *Signature equality over every stream:* of the 271,637 BVH streams of `core_bvh4.rpf`, 242,388 have a model whose
rule-kept triangle counts equal the stream's signature exactly (96,267 of the 125,180 streams with at least two
geometries and 64 triangles). Every other bucket set scores lower: keeping 0 and 3 but not 128 and 131 gives
240,984; keeping every geometry 197,117; keeping bucket 0 only 208,364; adding 1 to the kept set 228,214; adding 2
204,227; adding any of 4, 5, 6, 129 or 130 lowers the count by 5 to 128 streams. Second-LOD BLAS and drawables
outside the export cannot match a first-LOD export, so the rest are not counted against the rule.
* *Geometry check:* of 300 random exact hits (at least two geometries, at most 40,000 triangles), 241 pass
`bvh_geometry_check.py` with the instance transform, and 59 do not. Those 59 have the same triangle counts as a
drawable that is not where the BLAS is (the check tests the geometry, not the counts); the checker tries at most 8
models per stream.
* *Exceptions:* 511 such streams have no exact hit but match a model with one geometry's choice flipped. For 22 of
them that flipped candidate passes the geometry check: 34 geometries of bucket 1 (13) or 2 (21) that the BVH keeps.
No consistent candidate leaves out a bucket-0 or bucket-3 geometry. So the rule fails on at least 22 BLAS, always by
keeping a bucket-1 or bucket-2 geometry. What else marks those geometries is **open**.
* *Shader hashes:* of the 309 shader-group hashes the export's geometries use, 212 occur only in kept buckets, 96 only
in left-out ones, and 1 in both (87 geometries in bucket 0, 1 each in buckets 1 and 2). That is why a hash list
cannot express the rule, and it is probably the one hash below that the interior's 130 BLAS both keep and leave out.
The note below says those 3 left-out geometries have the same bucket as the kept ones; that was not re-measured
here, and if it holds they belong with the exceptions above.
`tools/bvh_match.py` applies the rule by default whenever every geometry of a model has a bucket in the manifest
(`--no-bucket-rule` turns it off; `--skip-shaders` still adds hashes on top).
**How a match is verified.** A byte-identical library result checks the packing, not the geometry: the model and
the library agree on any input. These checks use what the dehydrated stream recorded from the true geometry:
@ -640,8 +677,7 @@ converse fails: 1,008 (BLAS header, transform) pairs occur under more than one k
can share both the BLAS and its transform: the key identifies something finer than that pair. What it hashes is open;
#4199 (open) finds no more matches between these keys and the values of the table descriptors than chance gives.
**Open:** what decides which geometries the BVH leaves out (13 shader hashes over the interior's 130 BLAS, and one
hash both kept and left out); what decides the LOD a BLAS is built from; what the rest of the band of streams 231,012
**Open:** why the BVH keeps the bucket-1 and bucket-2 geometries of at least 22 BLAS (ASSET-349 above); what decides the LOD a BLAS is built from; what the rest of the band of streams 231,012
to 261,585 holds, and how the pack is ordered; why 4 exported archetypes with a kept shader have no BLAS; what
the descriptor key at `+0x40` hashes; how the game picks the entity of a BLAS when the BLAS does not name it (the
drawable match does it here); whether the game composes TLAS instances as `I * E * M^-1`; whether the runtime
@ -788,9 +824,9 @@ export rather than a second decoder. It reads the leaf signature (triangles per
primitives counting as two), keeps every (drawable, model) of a `rpf9dump models` manifest whose per-geometry triangle
counts contain that signature as an ordered subsequence, and checks the survivors with
`tools/bvh_geometry_check.py` from the model's exported OBJ and the 3x4 at `+0x50` of the instance descriptor. The
geometries of the shaders the BVH leaves out are filtered with `--skip-shaders`: those name hashes are game data,
as §4a says, so the rule is off unless the user passes them. A geometry whose shader index the manifest cannot resolve
keeps its place and the checks decide. Measured on the ten BLAS of the sample pack, against the first 1 GiB window of
geometries the BVH leaves out are filtered by render bucket (§4a, ASSET-349: kept when the low 7 bits are 0 or 3);
`--no-bucket-rule` turns that off and `--skip-shaders` adds shader name hashes on top (game data, local use only). A
model with a geometry whose bucket the manifest cannot resolve keeps every geometry and the checks decide. Measured on the ten BLAS of the sample pack, against the first 1 GiB window of
`levels.rpf` cut at 3 GB (exported as a whole slice): 1,228 models, 1 to 374 candidates from the signature per BLAS,
and exactly one consistent candidate each. A window holds one region's drawables, so a BLAS whose drawable is
elsewhere in the archive finds no candidate in it at all, and the tool says so instead of reporting a rejection. The
@ -805,7 +841,7 @@ from its own compression blocks; a sub-range is never written to the index cache
```powershell
dotnet build tools/rpf9dump/rpf9dump.csproj -c Release
dotnet tools/rpf9dump/bin/Release/net8.0/rpf9dump.dll models <levels.rpf> <out> --start 3221225472 --length 1073741824
python -I tools/bvh_match.py <dehydrated.bin> <out>/levels/models/manifest.json --descriptor <instance208.bin> [--skip-shaders H,H,...]
python -I tools/bvh_match.py <dehydrated.bin> <out>/levels/models/manifest.json --descriptor <instance208.bin> [--no-bucket-rule] [--skip-shaders H,H,...]
python -I tests/test_bvh_match.py
```

View File

@ -48,9 +48,13 @@ def write_obj(path, groups):
f.write("\n".join(lines) + "\n")
def item(offset, file, triangles, hashes=None):
"""One manifest row, as tools/rpf9dump writes it: per geometry triangles and shader index."""
def item(offset, file, triangles, hashes=None, buckets=None):
"""One manifest row, as tools/rpf9dump writes it: per geometry triangles and shader index, and with `buckets`
one render bucket per material (None leaves the field out, as an older export does)."""
materials = [{"ShaderIndex": i, "Shader": "%08X" % h} for i, h in enumerate(hashes or [])]
for material, bucket in zip(materials, buckets or []):
if bucket is not None:
material["RenderBucket"] = bucket
return {"Offset": offset, "File": file, "Name": "drawable_at_%X" % offset, "Meshes": len(triangles),
"Verts": 0, "Tris": sum(triangles), "MeshTris": list(triangles),
"MeshModels": [0] * len(triangles), "MeshGeoms": list(range(len(triangles))),
@ -103,7 +107,8 @@ class TestMatching(unittest.TestCase):
self.assertEqual(status, 0, out)
self.assertIn("triangles per geometry index: [2]", out)
self.assertIn("1 of 1 scored candidates are consistent", out)
self.assertIn("model 0 geometry [1] | outside 0 of 1", out)
self.assertIn("model 0 geometry [1] (bucket rule not applied: a geometry has no render bucket) | outside 0 of 1",
out)
def test_a_geometry_with_other_triangle_counts_is_not_a_candidate(self):
src, _, _ = build(LEAVES, bounds=BOUNDS)
@ -137,6 +142,70 @@ class TestMatching(unittest.TestCase):
["--skip-shaders", "%08X" % hashes[1]])
self.assertEqual(status, 1, out)
def test_the_bucket_rule_leaves_buckets_1_and_2_out(self):
src, _, _ = build(LEAVES, bounds=BOUNDS)
hashes = [0x11110000, 0x22220000, 0x33330000, 0x44440000]
# Buckets 1 and 2 are left out, so geometry 3 (bucket 3) is index 1 and geometry 0 (bucket 0) index 0; the
# BLAS's one leaf uses index 0 with two triangles, which only the bucket-0 geometry has once 1 and 2 are out.
files = {"a.obj": [group(2), group(2), group(2), group(9)]}
rows = [item(0x1000, "a.obj", [2, 2, 2, 9], hashes, [0, 1, 2, 3])]
self.assertEqual([mesh[5] for mesh in M.model_geometries(rows[0])], [0, 1, 2, 3])
candidates = M.match_candidates(rows, [2, 9], frozenset(), 8)
self.assertEqual([[c["kept"][k][0] for k in c["used"]] for c in candidates], [[0, 3]])
# Without the rule, [2, 9] also embeds through geometries 1 and 2.
loose = M.match_candidates(rows, [2, 9], frozenset(), 8, buckets=False)
self.assertEqual(sorted([c["kept"][k][0] for k in c["used"]] for c in loose), [[0, 3], [1, 3], [2, 3]])
status, out, _ = self.guide(src, rows, files)
self.assertEqual(status, 0, out)
self.assertIn("1 candidates", out)
self.assertIn("model 0 geometry [0] | outside 0 of 1", out)
def test_the_bucket_rule_finds_what_the_signature_alone_cannot(self):
# Signature [2, 5]: geometries 0 and 2 (bucket 0 and 3); geometry 1 (bucket 2, 5 triangles) is a decal the
# BVH leaves out. Without the rule the ordered match would also take geometry 1 for the 5.
rows = [item(0x1000, "a.obj", [2, 5, 5], [1, 2, 3], [0, 2, 3])]
self.assertEqual([[c["kept"][k][0] for k in c["used"]] for c in M.match_candidates(rows, [2, 5], frozenset(), 8)],
[[0, 2]])
self.assertEqual(len(M.match_candidates(rows, [2, 5], frozenset(), 8, buckets=False)), 2)
# A model all of whose geometries are left out has no candidate.
self.assertEqual(M.match_candidates([item(0x2000, "b.obj", [2], [1], [1])], [2], frozenset(), 8), [])
def test_the_bucket_rule_ignores_bit_7(self):
# 0x83 is bucket 3 with bit 7 set (kept); 0x82 is bucket 2 with bit 7 set (left out); 6 is left out.
rows = [item(0x1000, "a.obj", [4, 3, 3, 8], [1, 2, 3, 4], [0x83, 0x82, 6, 0x80])]
self.assertEqual([[c["kept"][k][0] for k in c["used"]] for c in M.match_candidates(rows, [4, 8], frozenset(), 8)],
[[0, 3]])
self.assertEqual(M.match_candidates(rows, [4, 3], frozenset(), 8), [])
def test_the_bucket_rule_is_not_applied_without_every_bucket(self):
src, _, _ = build(LEAVES, bounds=BOUNDS)
# Geometry 1 has no bucket: the rule cannot be applied, so the bucket-1 geometry stays a candidate.
rows = [item(0x1000, "a.obj", [2, 7], [1, 2], [1, None])]
status, out, _ = self.guide(src, rows, {"a.obj": [group(2), group(7)]})
self.assertEqual(status, 0, out)
self.assertIn("model 0 geometry [0] (bucket rule not applied", out)
def test_no_bucket_rule_keeps_every_geometry(self):
src, _, _ = build(LEAVES, bounds=BOUNDS)
rows = [item(0x1000, "a.obj", [2], [1], [2])]
status, out, _ = self.guide(src, rows, {"a.obj": [group(2)]})
self.assertEqual(status, 1, out)
self.assertIn("0 candidates", out)
status, out, _ = self.guide(src, rows, {"a.obj": [group(2)]}, ["--no-bucket-rule"])
self.assertEqual(status, 0, out)
self.assertIn("model 0 geometry [0] | outside 0 of 1", out)
def test_bucket_kept(self):
self.assertEqual([M.bucket_kept(b) for b in (0, 1, 2, 3, 4, 5, 6, None)],
[True, False, False, True, False, False, False, None])
# Bit 7 does not change the choice.
self.assertEqual([M.bucket_kept(b) for b in (0x80, 0x81, 0x82, 0x83)], [True, False, False, True])
def test_skip_shaders_still_applies_on_top_of_the_bucket_rule(self):
rows = [item(0x1000, "a.obj", [2, 2], [0xAAAA1111, 0xBBBB2222], [0, 0])]
candidates = M.match_candidates(rows, [2], frozenset([0xAAAA1111]), 8)
self.assertEqual([[c["kept"][k][0] for k in c["used"]] for c in candidates], [[1]])
def test_the_instance_transform_decides(self):
src, _, _ = build(LEAVES, bounds=(0.5, 0.0, 0.0, 1.5, 1.0, 0.0))
descriptor = os.path.join(self.dir, "instance208.bin")

View File

@ -12,9 +12,13 @@ came from has exactly those counts among the geometries of one of its models:
float32, faces are in primitive order) and check the rehydration against what the BLAS stores with
tools/bvh_geometry_check.py (bounds, overrides, paired-leaf edges, internal area).
The geometries whose shader the BVH leaves out are game data: pass their name hashes with --skip-shaders (or
BVH_SKIP_SHADERS). When a geometry's shader index is not in the manifest's material list the rule cannot be applied
to that drawable, and every geometry is a candidate; the checks then decide.
Which geometries the BVH leaves out follows from their material's render bucket (docs/bvh.md §4a, ASSET-349): the
byte at +57 of the shader record, which `rpf9dump models` writes as `RenderBucket`. A geometry is kept when the low 7
bits of that byte are 0 or 3 and left out otherwise (KEPT_BUCKETS; bit 7 is ignored). When a geometry of a
model has no bucket in the manifest (its shader index is not in the material list, or an older export without the
field) the rule cannot be applied to that model and every geometry is a candidate; the checks then decide.
--no-bucket-rule turns it off. --skip-shaders (or BVH_SKIP_SHADERS) still leaves out geometries by shader name hash
on top of it; the hashes are game data, for local use only.
The instance transform is the 3x4 at +0x50 of the BLAS's 208-byte instance descriptor (docs/bvh.md §3.2). Without
it, every leaf of a rotated structure falls outside the header bounds and a correct geometry is rejected.
@ -29,7 +33,7 @@ candidate is consistent, 1 when none is, and 2 on an input error.
Usage:
python -I tools/bvh_match.py <dehydrated.bin> <manifest.json> --descriptor <instance208.bin>
[--models DIR] [--header-offset N] [--descriptor-offset N]
[--transform 12 floats] [--skip-shaders HEX,HEX] [--unordered]
[--transform 12 floats] [--skip-shaders HEX,HEX] [--no-bucket-rule] [--unordered]
[--embeddings N] [--top N] [--names] [--write DIR] [--json FILE]
--write DIR writes the matched geometries as float3/uint32 buffers plus an export.json, the shape
@ -49,6 +53,16 @@ from report_paths import same_report_path # noqa: E402
INSTANCE_TRANSFORM_OFFSET = 0x50
SKIP_SHADERS_ENV = "BVH_SKIP_SHADERS"
# Render buckets (low 7 bits of the byte at shader record +57, `RenderBucket` in the manifest) whose geometries the
# BVH keeps; every other bucket (1, 2, 4, 5, 6) is left out. Bit 7 does not change the choice (docs/bvh.md §4a,
# ASSET-349).
KEPT_BUCKETS = frozenset((0, 3))
BUCKET_MASK = 0x7F
def bucket_kept(bucket):
"""True when the BVH keeps a geometry whose material has this render bucket, None when the bucket is unknown."""
return None if bucket is None else (bucket & BUCKET_MASK) in KEPT_BUCKETS
def leaf_signature(src, header_offset=0):
@ -120,7 +134,8 @@ def embeddings(signature, counts, cap, ordered=True):
def model_geometries(item):
"""[(mesh index, model, geometry, triangles, shader hash or None)] for one manifest item, in mesh order.
"""[(mesh index, model, geometry, triangles, shader hash or None, render bucket or None)] for one manifest item,
in mesh order.
The mesh index is the geometry's `o` group in the item's OBJ: the manifest arrays and the OBJ groups are
written in the same order.
@ -132,29 +147,36 @@ def model_geometries(item):
geometries = item.get("MeshGeoms") or list(range(len(tris)))
shaders = item.get("MeshShaders") or [None] * len(tris)
materials = item.get("Materials") or []
hashes = []
hashes, buckets = [], []
for index in shaders:
if index is None or not 0 <= index < len(materials) or "Shader" not in materials[index]:
hashes.append(None)
else:
hashes.append(int(materials[index]["Shader"], 16))
return list(zip(range(len(tris)), models, geometries, tris, hashes))
material = materials[index] if index is not None and 0 <= index < len(materials) else {}
hashes.append(int(material["Shader"], 16) if "Shader" in material else None)
bucket = material.get("RenderBucket")
buckets.append(bucket if isinstance(bucket, int) and not isinstance(bucket, bool) else None)
return list(zip(range(len(tris)), models, geometries, tris, hashes, buckets))
def match_candidates(items, signature, skip, cap, ordered=True):
"""Every (item, model, used geometry indices, kept geometries) whose triangle counts contain the signature."""
def match_candidates(items, signature, skip, cap, ordered=True, buckets=True):
"""Every (item, model, used geometry indices, kept geometries) whose triangle counts contain the signature.
buckets: leave out the geometries whose render bucket the BVH does not keep (bucket_kept), in every model whose
geometries all have a bucket. skip: shader hashes left out as well, in every model whose geometries all have one.
"""
out = []
for item in items:
meshes = model_geometries(item)
for model in sorted({mesh[1] for mesh in meshes}):
group = [mesh for mesh in meshes if mesh[1] == model]
# A geometry whose shader is one of the excluded hashes is not in the BLAS, so it takes no index in the
# signature. Without every hash of the group the rule cannot be applied: keep all of them.
# A geometry the BVH leaves out is not in the BLAS, so it takes no index in the signature. Without the
# bucket (or, for --skip-shaders, the hash) of every geometry of the group a rule cannot be applied to
# it: keep all of them and let the checks decide.
by_bucket = buckets and all(mesh[5] is not None for mesh in group)
rule = bool(skip) and all(mesh[4] is not None for mesh in group)
kept = [mesh for mesh in group if not rule or mesh[4] not in skip]
kept = [mesh for mesh in group
if (not by_bucket or bucket_kept(mesh[5])) and (not rule or mesh[4] not in skip)]
for used in embeddings(signature, [mesh[3] for mesh in kept], cap, ordered):
out.append({"item": item, "model": model, "used": used, "kept": kept,
"rule": rule, "skipped": bool(skip)})
"rule": rule, "skipped": bool(skip), "by_bucket": by_bucket, "buckets": buckets})
return out
@ -255,6 +277,8 @@ def describe(candidate, names):
used = [candidate["kept"][k][2] for k in candidate["used"]]
label = ("%-40s " % item["Name"]) if names else ""
note = " (shader rule not applied)" if candidate["skipped"] and not candidate["rule"] else ""
if candidate.get("buckets") and not candidate.get("by_bucket"):
note += " (bucket rule not applied: a geometry has no render bucket)"
return "%sstream 0x%-10x model %d geometry %s%s" % (label, item["Offset"], candidate["model"], used, note)
@ -269,6 +293,8 @@ def main(argv=None):
ap.add_argument("--header-offset", type=int, default=0, help="the 64-byte header's offset in the file")
ap.add_argument("--skip-shaders", default=os.environ.get(SKIP_SHADERS_ENV, ""),
help="shader name hashes of the geometries the BVH leaves out (game data; local use only)")
ap.add_argument("--no-bucket-rule", action="store_true",
help="do not leave out geometries by render bucket (by default only buckets 0 and 3 are kept)")
ap.add_argument("--unordered", action="store_true", help="also try the geometries in any order")
ap.add_argument("--embeddings", type=int, default=64, help="at most this many index choices per model")
ap.add_argument("--top", type=int, default=8, help="how many scored candidates to print")
@ -308,7 +334,8 @@ def main(argv=None):
signature = leaf_signature(src, a.header_offset)
if not signature:
raise ValueError("the BLAS has no leaves")
candidates = match_candidates(items, signature, parse_shader_hashes(a.skip_shaders), a.embeddings, not a.unordered)
candidates = match_candidates(items, signature, parse_shader_hashes(a.skip_shaders), a.embeddings,
not a.unordered, not a.no_bucket_rule)
except (OSError, ValueError, KeyError, IndexError, TypeError, struct.error) as e:
print("error: %s" % e, file=sys.stderr)
return 2