upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tools
diff options
context:
space:
mode:
authorDiesel <dev.diesel@proton.me>2026-11-21 22:44:07 +0100
committerDiesel <dev.diesel@proton.me>2026-11-21 22:44:07 +0100
commit5c1a1fbb6bf6f609eb4e61baa4961ce382743a4e (patch)
treeac8ad90058b97ab241fdc65edae3d4628d20ee1e /tools
parentc45309e29f21c1d5b75678db0e2dc2dd11cff25b (diff)
parent4e390e0871d7265e629b51aca8ff99a15a6a6845 (diff)
Merge main to include the compute Y/Z harness test fix
Diffstat (limited to 'tools')
-rw-r--r--tools/awc_manifest.py9
-rw-r--r--tools/awc_opus.py32
-rw-r--r--tools/gamedata_xml.py568
-rw-r--r--tools/manifest.py15
-rw-r--r--tools/mc_command.py29
-rw-r--r--tools/rbf0_tree.py554
-rw-r--r--tools/rdna2spirv.py40
-rw-r--r--tools/root_sig_contract.py155
-rw-r--r--tools/rpf9_carve.py4
-rw-r--r--tools/shader_disasm.py26
-rw-r--r--tools/ttpf_mips.py845
-rw-r--r--tools/world_census.py697
12 files changed, 2922 insertions, 52 deletions
diff --git a/tools/awc_manifest.py b/tools/awc_manifest.py
index 27bf7b625..f8df52952 100644
--- a/tools/awc_manifest.py
+++ b/tools/awc_manifest.py
@@ -13,8 +13,9 @@ streamed_music, data_offset, data_size, bank_size, notes. JSON is an object with
13stream_count, streamed_music_channel_count and a streams list of the same fields (booleans and 13stream_count, streamed_music_channel_count and a streams list of the same fields (booleans and
14numbers keep their types). duration_s is the AWC header's declared samples / sample rate; notes 14numbers keep their types). duration_s is the AWC header's declared samples / sample rate; notes
15flags values that look inconsistent (zero/odd rate, data-size mismatch, implausible duration). 15flags values that look inconsistent (zero/odd rate, data-size mismatch, implausible duration).
16A streamed-music descriptor contributes one row per mono channel; data_offset/size is its shared 16A streamed-music descriptor contributes one row per channel group; `channels` is the packet channel count read
17data tag. 17from the Opus TOC stereo bit, and `declared_samples`/`duration_s` are per channel (the descriptor stores the
18interleaved count). `data_offset`/`size` is the shared data tag.
18""" 19"""
19import argparse 20import argparse
20import csv 21import csv
@@ -108,8 +109,8 @@ def _bank_rows(path: str) -> list:
108 print(f"awc_manifest: warning: {bank}: ignored malformed streamed-music descriptor", 109 print(f"awc_manifest: warning: {bank}: ignored malformed streamed-music descriptor",
109 file=sys.stderr) 110 file=sys.stderr)
110 continue 111 continue
111 for cid, samples, rate, codec, _packets in channels: 112 for cid, samples, rate, codec, _packets, packet_channels in channels:
112 rows[cid] = _row(bank, cid, codec, 1, rate, samples, data, bank_size, True) 113 rows[cid] = _row(bank, cid, codec, packet_channels, rate, samples, data, bank_size, True)
113 return list(rows.values()) 114 return list(rows.values())
114 115
115 116
diff --git a/tools/awc_opus.py b/tools/awc_opus.py
index b43a796f0..2f2156220 100644
--- a/tools/awc_opus.py
+++ b/tools/awc_opus.py
@@ -6,13 +6,15 @@ AWC layout (little-endian "ADAT"), as read by rpf9-explorer's OpusPreview.cpp: a
6(id[28:0] | tag count[31:29]), then 8-byte tags (type[63:56], size[55:28], offset[27:0]). Tag 0x55 = data, 6(id[28:0] | tag count[31:29]), then 8-byte tags (type[63:56], size[55:28], offset[27:0]). Tag 0x55 = data,
70x76 = format (u32 samples, u16 rate at +8, codec at +28, channels at +29). Codec 0x0B = Opus at 48 kHz: data is 70x76 = format (u32 samples, u16 rate at +8, codec at +28, channels at +29). Codec 0x0B = Opus at 48 kHz: data is
82048-byte blocks of [u16 length][packet] ..., a zero length pads the rest of the block. Codec 0 = PCM16 (written as 82048-byte blocks of [u16 length][packet] ..., a zero length pads the rest of the block. Codec 0 = PCM16 (written as
9.wav). Codec 2 = 32-bit float PCM (float .wav). Streamed music (tag 0x48, multi-channel interleaved blocks) is not handled here yet. 9.wav). Codec 2 = 32-bit float PCM (float .wav).
10 10
11Streamed music (tag 0x48 descriptor: u32 blocks, u32 chunk size, u32 channels, then 16 bytes per channel: id, 11Streamed music (tag 0x48 descriptor: u32 blocks, u32 chunk size, u32 channels, then 16 bytes per channel: id,
12samples, rate at +10, codec at +12) is split into one mono Ogg Opus per channel: each chunk starts with a 12samples, rate at +10, codec at +12) is split into one Ogg Opus per descriptor channel: each chunk starts with a
1324-byte record per channel (subblock count at +4, repeated-prefix samples to skip at +8), the channel data are 1324-byte record per channel (subblock count at +4, repeated-prefix samples to skip at +8), the channel data are
14its run of 2048-byte subblocks after the 2048-aligned header, and the first `skip` samples of a chunk repeat the 14its run of 2048-byte subblocks after the 2048-aligned header, and the first `skip` samples of a chunk repeat the
15previous chunk's tail and are dropped (whole packets). 15previous chunk's tail and are dropped (whole packets). The descriptor's `channels` is the number of channel
16groups, not necessarily the packet channel count: an Opus packet's TOC stereo bit gives the real channel count,
17and the descriptor's `samples` counts interleaved samples across those packet channels.
16 18
17Output: <out>/<bank>/<stream id>.ogg (or .wav), plus a summary line per bank. 19Output: <out>/<bank>/<stream id>.ogg (or .wav), plus a summary line per bank.
18 20
@@ -156,7 +158,11 @@ def parse_awc(d: bytes):
156 158
157 159
158def music_channels(d: bytes, mus, data, collect_packets: bool = True): 160def music_channels(d: bytes, mus, data, collect_packets: bool = True):
159 """[(channel id, samples, rate, codec, [packets])] for one streamed-music descriptor. 161 """[(channel id, samples, rate, codec, [packets], packet channels)] for one streamed-music descriptor.
162
163 `samples` is the per-channel frame count. The descriptor stores the interleaved sample count, so it is
164 divided by the packet channel count when the Opus packets are stereo. `packet channels` is read from the
165 Opus TOC stereo bit (bit 2) and defaults to 1 when no packet is present.
160 166
161 collect_packets=False keeps the packet lists empty for metadata-only callers (awc_manifest.py).""" 167 collect_packets=False keeps the packet lists empty for metadata-only callers (awc_manifest.py)."""
162 (m_at, m_size), (d_at, d_size) = mus, data 168 (m_at, m_size), (d_at, d_size) = mus, data
@@ -169,7 +175,7 @@ def music_channels(d: bytes, mus, data, collect_packets: bool = True):
169 cid = struct.unpack_from("<I", d, base)[0] & 0x1FFFFFFF 175 cid = struct.unpack_from("<I", d, base)[0] & 0x1FFFFFFF
170 samples, = struct.unpack_from("<I", d, base + 4) 176 samples, = struct.unpack_from("<I", d, base + 4)
171 rate, = struct.unpack_from("<H", d, base + 10) 177 rate, = struct.unpack_from("<H", d, base + 10)
172 info.append([cid, samples, rate, d[base + 12], []]) 178 info.append([cid, samples, rate, d[base + 12], [], 0])
173 for b in range(blocks): 179 for b in range(blocks):
174 at = d_at + b * chunk 180 at = d_at + b * chunk
175 recs = [struct.unpack_from("<III", d, at + 24 * c + 4)[:2] for c in range(channels)] # (count, skip) 181 recs = [struct.unpack_from("<III", d, at + 24 * c + 4)[:2] for c in range(channels)] # (count, skip)
@@ -179,14 +185,22 @@ def music_channels(d: bytes, mus, data, collect_packets: bool = True):
179 for c, (count, skip) in enumerate(recs): 185 for c, (count, skip) in enumerate(recs):
180 start = at + header + before * 2048 186 start = at + header + before * 2048
181 before += count 187 before += count
182 if info[c][3] != 0x0B or count == 0 or not collect_packets: 188 if info[c][3] != 0x0B or count == 0:
189 continue
190 packets = opus_packets(d, start, count * 2048)
191 if packets and info[c][5] == 0:
192 info[c][5] = 2 if any(p[0] & 0x04 for p in packets) else 1
193 if not collect_packets:
183 continue 194 continue
184 for pk in opus_packets(d, start, count * 2048): 195 for pk in packets:
185 n = opus_samples(pk) 196 n = opus_samples(pk)
186 if skip >= n and skip > 0: 197 if skip >= n and skip > 0:
187 skip -= n 198 skip -= n
188 continue 199 continue
189 info[c][4].append(pk) 200 info[c][4].append(pk)
201 for x in info:
202 if x[3] == 0x0B and x[5] > 1:
203 x[1] //= x[5]
190 return [tuple(x) for x in info] 204 return [tuple(x) for x in info]
191 205
192 206
@@ -213,10 +227,10 @@ def export_bank(path: str, out_dir: str):
213 counts = {"opus": 0, "pcm": 0, "other": 0, "music": 0} 227 counts = {"opus": 0, "pcm": 0, "other": 0, "music": 0}
214 streams, music = parse_awc(d) 228 streams, music = parse_awc(d)
215 for mus, data in music: 229 for mus, data in music:
216 for cid, samples, rate, codec, pk in music_channels(d, mus, data): 230 for cid, samples, rate, codec, pk, packet_channels in music_channels(d, mus, data):
217 if pk: 231 if pk:
218 n48 = samples * 48000 // rate if rate else 0 232 n48 = samples * 48000 // rate if rate else 0
219 write_ogg_opus(os.path.join(od, f"{cid:08X}.ogg"), pk, 1, cid, n48) 233 write_ogg_opus(os.path.join(od, f"{cid:08X}.ogg"), pk, packet_channels, cid, n48)
220 counts["music"] += 1 234 counts["music"] += 1
221 for s in streams: 235 for s in streams:
222 at, size = s["data"] 236 at, size = s["data"]
diff --git a/tools/gamedata_xml.py b/tools/gamedata_xml.py
new file mode 100644
index 000000000..0b71fe41e
--- /dev/null
+++ b/tools/gamedata_xml.py
@@ -0,0 +1,568 @@
1"""Catalog the XML documents recovered from a carved RPF9 archive.
2
3RPF9 stores a logical XML document as one or more zlib streams. A carve from ``rpf9_carve.py`` has an
4``index.json`` plus one inflated ``<offset>.bin`` per stream, so ``gamedata_index.py`` can group the streams
5back into payloads. This tool parses those payloads and writes an aggregate catalog:
6
7 python -I gamedata_xml.py <carve_dir> [--csv FILE] [--json FILE] [--check]
8 python -I gamedata_xml.py <file.xml> [<file.xml> ...] [--csv FILE] [--json FILE] [--check]
9
10For every file it records the root element, element count, maximum depth, attribute names, ``$(name)`` and
11``platform:/`` references, and include-like structures. For every root it records the file count, category,
12element-name histogram, attribute histogram and reference targets. ``--check`` validates well-formedness and
13separates rootless fragments, tail-only documents and malformed documents.
14
15Only schema names, element/attribute names and reference tokens are written. Element text, attribute values,
16``type``/``content`` values and entry paths are not. For a carve directory a row is identified by offset; an
17individual file is identified by the basename that was passed. The output is a local work product: it must not
18be committed or attached to an issue. The test fixtures are synthetic and contain no game data.
19"""
20import argparse
21import csv
22import io
23import json
24import os
25import re
26import statistics
27import sys
28import xml.etree.ElementTree as ET
29from collections import Counter, defaultdict
30
31ROOT = os.path.dirname(os.path.abspath(__file__))
32if ROOT not in sys.path:
33 sys.path.insert(0, ROOT)
34import gamedata_index as gi # noqa: E402
35
36BOM = b"\xef\xbb\xbf"
37MACRO_REF = re.compile(r"\$\(([A-Za-z_][\w.-]*)\)")
38PLATFORM_REF = re.compile(r"platform:/([A-Za-z0-9_.-]+)?")
39XI_INCLUDE = "{http://www.w3.org/2001/XInclude}include"
40INCLUDE_ELEMENTS = ("fileList", "filename", "includedSets", "includedChangesets",
41 "changesetIncludeFlags", "loadPath")
42
43# Category names and root membership follow the functional table in docs/gamedata.md. A category is a
44# dispatch hint: the same root always belongs to one bucket, but a bucket is not a complete schema. Where a
45# document straddles two labels, the table's bucket is kept so the file and root counts line up.
46CATEGORY_ROOTS = {
47 "time, weather, sky, water": """
48 timecycle_modifier_data timecycle_keyframe_data CContentsOfWeatherXmlFile STS_Config CustomClouds
49 CScatteringTransmittance__FogVolumeListData FogVolumeProfileList OceanSimPresets
50 OceanWaveCalmingCurves EnvironmentalWaterDisturbManager ShoreWavePlacementData time_data
51 RegionTintMap
52 """,
53 "vehicles, tyres, handling data": """
54 CVehiclePoints CVehicleBoneOffsetsArray CVehiclePerformanceMaps CVehicleBaseRatingsAndEstimatesMap
55 CVehicleComponentSetManager CVehicleDistantLightData CVehiclePointsMeta CTyreDataSet CParkingSplines
56 CSnowTrackData CBreakableVehicleDoorLockManagerData CPaletteIndexedRecipeTintsArray
57 """,
58 "peds, schedules, appearance": """
59 CPedAccuracyManager CPedComponentSetManager CPedFormationInfoManager CPedHeadbobSettingsManager
60 CPedInventoryLoadOutManager CPedMoodConditionTreesManager CPedMoodSettingsManager
61 CPedMotivationInfoManager CPedScheduleInfoManager CPedSpeedDataBlock CPedTimeWarpSettingsManager
62 CPedVariationBodyTypeManager CPairedPedDataBlock CEnergyConfigInfos CIdlePreferenceManager
63 CUpperBodyIdleConditionManager CUpperBodyIdleSettingsManager CHeadbobConditionManager
64 CHealthConfigInfo sPedDamageModifiers sPedDistractionModifiers WalkAndTalkProfileData
65 STPedMotionPredictionSetContainer STPedNavigationPredictiontPresetContainer CBaitingInfo
66 CAnimalAnimationContexts CAnimalAttackBehaviours Relationships__GroupsData CMoodConditionManager
67 """,
68 "tuning, parameters, effects": """
69 CTuningFile CCoverProcessorTuning GridAtlasInfo PatchConstants CClimbTuneMgr CoverShadowTunables
70 LostTargetSearch__Tunables sCollisionEventScannerTuning hrsSimTuneMgr rage__fragTuneStruct
71 DiffractionProfiles GlintsProfiles LightAnimationPresets CGraphicsDefinitionsData
72 """,
73 "mount / content manifests": """
74 CDataFileMgr__ContentChangeSetDef CDataFileMgr__ContentDef
75 """,
76 "world, navigation, map": """
77 GameShape__Data__LocationNameLoopkup PathingStyleData CTrainConfigs CHazardNodes
78 MapState__Data__Templates aiNavIMapGroupData CLadderMetadataManager CLadderRailsMetadataManager
79 CDoorInteractionDataList CEntityComponentLodManagerData CGarageInitDataList
80 CSceneTerrainAnalyzerMgrDataInstance CScenicViewManager MaterialDataList TextureGridInfo
81 Sprinklers__RootData CProceduralInfo CFluidVesselManager CObjectComponentSetManager
82 """,
83 "combat and AI behaviour": """
84 CCombatInfoMgr CFiringPatternInfoManager CFleeDecisionMakerData Combat__GoalData__Store
85 CSearchPointOfInterestRuleSet CTacticalAnalysisDistributionStore
86 Modular__SM__AIBehaviour__LockControllerConfig Witnesses__Informations CTaskDataInfoManager
87 CDrivingStyleCollection CLassoDataManager CAimUpperBodyDataBlock SSetupData
88 """,
89 "animation, poses, weapons": """
90 WeaponAnimations__FullbodyControllerData WeaponAnimations__ConfigData CStandardPosesManager
91 CAnimSceneAttachSlotSetManager StudioConfigurationData rage__fwRetargetCoordinatorConfig
92 """,
93 "damage": "CDamageDataManager",
94 "audio, video, speech": """
95 LandingPageVideos CTVPlaylistContainer naSpeechEventTypeBatchRequestParams rage__MediaDecoderSettings
96 """,
97 "missions, scenarios, respawn": "CDynamicScenarioManager CMissions Respawn__MetaData",
98 "conversation": "CConversationList CConversationDictionary",
99}
100CATEGORY_BY_ROOT = {}
101for _category, _roots in CATEGORY_ROOTS.items():
102 for _root in _roots.split():
103 CATEGORY_BY_ROOT[_root] = _category
104UNCATALOGUED = "uncatalogued"
105
106
107def category_for(root: str) -> str:
108 return CATEGORY_BY_ROOT.get(root, UNCATALOGUED)
109
110
111def scan_refs(text: str, report: dict) -> None:
112 """Count symbolic macros and platform prefixes in one text or attribute value."""
113 if not text:
114 return
115 if "$(" in text:
116 for match in MACRO_REF.finditer(text):
117 report["refs"]["$(" + match.group(1) + ")"] += 1
118 if "platform:/" in text:
119 for match in PLATFORM_REF.finditer(text):
120 # Keep the bucket coarse: the first segment after a platform prefix can be a directory or a
121 # file-like archive name, and only levels/other is needed to route a mount.
122 report["platform"]["levels" if (match.group(1) or "").lower() == "levels" else "other"] += 1
123 report["platform_total"] += 1
124
125
126def scan_xml(data: bytes) -> dict:
127 """Parse one document and return aggregate facts. Never keeps element text or values."""
128 report = {
129 "root": "",
130 "well_formed": False,
131 "error": "",
132 "element_count": 0,
133 "max_depth": 0,
134 "attributes": [],
135 "comments": data.count(b"<!--"),
136 "elements": Counter(),
137 "attrs": Counter(),
138 "refs": Counter(),
139 "platform": Counter(),
140 "platform_total": 0,
141 "filename": 0,
142 "parent_path": 0,
143 "parent_file": 0,
144 "xi_include": 0,
145 "type_attrs": 0,
146 "type_values": set(),
147 "content_values": set(),
148 }
149 depth = 0
150 try:
151 parser = ET.iterparse(io.BytesIO(data), events=("start", "end"))
152 for event, elem in parser:
153 if event == "start":
154 depth += 1
155 report["max_depth"] = max(report["max_depth"], depth)
156 if not report["root"]:
157 report["root"] = elem.tag
158 report["element_count"] += 1
159 report["elements"][elem.tag] += 1
160 for name, value in elem.attrib.items():
161 report["attrs"][name] += 1
162 if name == "type":
163 report["type_attrs"] += 1
164 report["type_values"].add(value)
165 elif name == "content":
166 report["content_values"].add(value)
167 elif name == "parentPath":
168 report["parent_path"] += 1
169 elif name == "parentFile":
170 report["parent_file"] += 1
171 scan_refs(value, report)
172 if elem.tag == "filename":
173 report["filename"] += 1
174 if elem.tag == XI_INCLUDE or elem.tag == "xi:include":
175 report["xi_include"] += 1
176 else:
177 scan_refs(elem.text, report)
178 scan_refs(elem.tail, report)
179 depth -= 1
180 elem.clear()
181 report["well_formed"] = True
182 except ET.ParseError as exc:
183 # ET errors carry a line/column and a short reason, never the element content.
184 report["error"] = str(exc)
185 report["attributes"] = sorted(report["attrs"])
186 return report
187
188
189def looks_truncated(data: bytes, root: str) -> bool:
190 """True when the bytes start inside a document instead of at its root element."""
191 if not root:
192 return False
193 body = data[3:] if data.startswith(BOM) else data
194 body = body.lstrip(b" \t\r\n")
195 if body.startswith(b"<?xml"):
196 return False
197 return gi.xml_root(data) != root
198
199
200def file_row(doc: dict, scan: dict) -> dict:
201 # A truncated tail can begin with an inner element, so the index's closing-root hint wins.
202 root = doc.get("root_hint") or scan["root"]
203 header = doc.get("header")
204 if header is None:
205 header = gi.has_xml_decl(doc["data"])
206 if doc.get("from_carve"):
207 tail_only = not header
208 fragment = not root or not doc.get("complete", True)
209 else:
210 tail_only = not scan["well_formed"] and looks_truncated(doc["data"], root)
211 fragment = not root
212 malformed = not scan["well_formed"] and not tail_only and not fragment
213 row = {
214 "source": doc.get("name", ""),
215 "offset": doc.get("offset"),
216 "offset_hex": doc.get("offset_hex", ""),
217 "bytes": len(doc["data"]),
218 "chunks": doc.get("chunks", 1),
219 "root": root,
220 "category": category_for(root) if root else UNCATALOGUED,
221 "header": bool(header),
222 "complete": doc.get("complete", scan["well_formed"]),
223 "well_formed": scan["well_formed"],
224 "fragment": fragment,
225 "tail_only": tail_only and not fragment,
226 "truncated": tail_only and not fragment and not scan["well_formed"],
227 "malformed": malformed,
228 "error": scan["error"],
229 "element_count": scan["element_count"] if scan["well_formed"] else None,
230 "max_depth": scan["max_depth"] if scan["well_formed"] else None,
231 "comments": scan["comments"],
232 "attributes": scan["attributes"],
233 "refs": dict(sorted(scan["refs"].items())),
234 "platform": dict(sorted(scan["platform"].items())),
235 "platform_total": scan["platform_total"],
236 "filename": scan["filename"],
237 "parent_path": scan["parent_path"],
238 "parent_file": scan["parent_file"],
239 "xi_include": scan["xi_include"],
240 "type_attrs": scan["type_attrs"],
241 "type_values": len(scan["type_values"]),
242 "content_values": len(scan["content_values"]),
243 }
244 row["_scan"] = scan
245 return row
246
247
248def new_root_stats(root: str) -> dict:
249 return {
250 "root": root,
251 "category": category_for(root) if root else UNCATALOGUED,
252 "files": 0,
253 "well_formed": 0,
254 "fragments": 0,
255 "tail_only": 0,
256 "truncated": 0,
257 "malformed": 0,
258 "bytes": 0,
259 "elements": 0,
260 "max_depth": 0,
261 "element_names": Counter(),
262 "attributes": Counter(),
263 "refs": Counter(),
264 "platform": Counter(),
265 "platform_total": 0,
266 "filename": 0,
267 "parent_path": 0,
268 "parent_file": 0,
269 "xi_include": 0,
270 "type_attrs": 0,
271 "type_values": set(),
272 "content_values": set(),
273 }
274
275
276def aggregate(rows: list) -> dict:
277 roots = {}
278 for row in rows:
279 stats = roots.setdefault(row["root"], new_root_stats(row["root"]))
280 stats["files"] += 1
281 stats["bytes"] += row["bytes"]
282 stats["fragments"] += int(row["fragment"])
283 stats["tail_only"] += int(row["tail_only"])
284 stats["truncated"] += int(row["truncated"])
285 stats["malformed"] += int(row["malformed"])
286 if not row["well_formed"]:
287 continue
288 scan = row["_scan"]
289 stats["well_formed"] += 1
290 stats["elements"] += scan["element_count"]
291 stats["max_depth"] = max(stats["max_depth"], scan["max_depth"])
292 stats["element_names"].update(scan["elements"])
293 stats["attributes"].update(scan["attrs"])
294 stats["refs"].update(scan["refs"])
295 stats["platform"].update(scan["platform"])
296 stats["platform_total"] += scan["platform_total"]
297 stats["filename"] += scan["filename"]
298 stats["parent_path"] += scan["parent_path"]
299 stats["parent_file"] += scan["parent_file"]
300 stats["xi_include"] += scan["xi_include"]
301 stats["type_attrs"] += scan["type_attrs"]
302 stats["type_values"].update(scan["type_values"])
303 stats["content_values"].update(scan["content_values"])
304
305 total_elements = Counter()
306 total_attributes = Counter()
307 total_refs = Counter()
308 total_platform = Counter()
309 all_type_values = set()
310 all_content_values = set()
311 by_category = defaultdict(lambda: {"files": 0, "roots": 0, "elements": 0, "bytes": 0})
312 for root, stats in roots.items():
313 total_elements.update(stats["element_names"])
314 total_attributes.update(stats["attributes"])
315 total_refs.update(stats["refs"])
316 total_platform.update(stats["platform"])
317 all_type_values.update(stats["type_values"])
318 all_content_values.update(stats["content_values"])
319 cat = by_category[stats["category"]]
320 cat["files"] += stats["files"]
321 cat["roots"] += 1
322 cat["elements"] += stats["elements"]
323 cat["bytes"] += stats["bytes"]
324
325 for stats in roots.values():
326 stats["element_names"] = dict(sorted(stats["element_names"].items(), key=lambda kv: (-kv[1], kv[0])))
327 stats["attributes"] = dict(sorted(stats["attributes"].items(), key=lambda kv: (-kv[1], kv[0])))
328 stats["refs"] = dict(sorted(stats["refs"].items()))
329 stats["platform"] = dict(sorted(stats["platform"].items()))
330 stats["type_values"] = len(stats["type_values"])
331 stats["content_values"] = len(stats["content_values"])
332
333 ordered_roots = dict(sorted(roots.items(), key=lambda kv: (-kv[1]["files"], kv[0])))
334 return {
335 "roots": ordered_roots,
336 "elements": total_elements,
337 "attributes": total_attributes,
338 "refs": total_refs,
339 "platform": total_platform,
340 "type_values": len(all_type_values),
341 "content_kinds": len(all_content_values),
342 "categories": dict(sorted(by_category.items())),
343 }
344
345
346def summarize(rows: list, agg: dict, mode: str) -> dict:
347 sizes = sorted(row["bytes"] for row in rows)
348 header_sizes = sorted(row["bytes"] for row in rows if row["header"])
349 return {
350 "mode": mode,
351 "documents": len(rows),
352 "well_formed": sum(1 for row in rows if row["well_formed"]),
353 "fragments": sum(1 for row in rows if row["fragment"]),
354 "tail_only": sum(1 for row in rows if row["tail_only"]),
355 "truncated": sum(1 for row in rows if row["truncated"]),
356 "malformed": sum(1 for row in rows if row["malformed"]),
357 "root_count": sum(1 for root in agg["roots"] if root),
358 "unattributed": int("" in agg["roots"]),
359 "catalog_roots": sum(1 for root in agg["roots"] if root in CATEGORY_BY_ROOT),
360 "elements": sum(agg["elements"].values()),
361 "element_names": len(agg["elements"]),
362 "attributes": len(agg["attributes"]),
363 "max_depth": max((stats["max_depth"] for stats in agg["roots"].values()), default=0),
364 "comments": sum(row["comments"] for row in rows),
365 "comments_header": sum(row["comments"] for row in rows if row["header"]),
366 "header_documents": len(header_sizes),
367 "type_values": agg["type_values"],
368 "content_kinds": agg["content_kinds"],
369 "bytes": sum(sizes),
370 "min_bytes": sizes[0] if sizes else 0,
371 "median_bytes": int(statistics.median(sizes)) if sizes else 0,
372 "max_bytes": sizes[-1] if sizes else 0,
373 "header_bytes": {
374 "min": header_sizes[0] if header_sizes else 0,
375 "median": int(statistics.median(header_sizes)) if header_sizes else 0,
376 "max": header_sizes[-1] if header_sizes else 0,
377 },
378 "references": dict(sorted(agg["refs"].items())),
379 "platform": dict(sorted(agg["platform"].items())),
380 "platform_total": sum(agg["platform"].values()),
381 "filename": sum(stats["filename"] for stats in agg["roots"].values()),
382 "parent_path": sum(stats["parent_path"] for stats in agg["roots"].values()),
383 "parent_file": sum(stats["parent_file"] for stats in agg["roots"].values()),
384 "xi_include": sum(stats["xi_include"] for stats in agg["roots"].values()),
385 "include_like": {name: agg["elements"].get(name, 0) for name in INCLUDE_ELEMENTS},
386 "categories": agg["categories"],
387 "catalog": {
388 "roots": len(CATEGORY_BY_ROOT),
389 "categories": len(CATEGORY_ROOTS),
390 },
391 }
392
393
394def carve_documents(directory: str):
395 """Yield the XML payloads of an rpf9_carve.py directory, rebuilt by gamedata_index."""
396 source = gi.DirectorySource(directory)
397 rows = gi.build_rows(source.rows, source)
398 by_offset = {row["off"]: index for index, row in enumerate(source.rows)}
399 for row in rows:
400 if row["type"] != "xml":
401 continue
402 start = by_offset[row["offset"]]
403 data = b"".join(source.read(source.rows[index]) for index in range(start, start + row["chunks"]))
404 yield {
405 "data": data,
406 "from_carve": True,
407 "offset": row["offset"],
408 "offset_hex": row["offset_hex"],
409 "chunks": row["chunks"],
410 "header": row["header"],
411 "complete": row["complete"],
412 "root_hint": row["root"],
413 }
414
415
416def xml_files(directory: str):
417 for base, _, names in os.walk(directory):
418 for name in sorted(names):
419 if name.lower().endswith(".xml"):
420 yield os.path.join(base, name)
421
422
423def document_mode(targets: list) -> str:
424 for target in targets:
425 if os.path.isdir(target) and os.path.isfile(os.path.join(target, "index.json")):
426 return "carve"
427 return "files"
428
429
430def load_documents(targets: list):
431 """Yield one document per XML payload. Directories with index.json use the carve path."""
432 for target in targets:
433 if os.path.isdir(target):
434 if os.path.isfile(os.path.join(target, "index.json")):
435 for doc in carve_documents(target):
436 yield doc
437 else:
438 for path in xml_files(target):
439 yield file_document(path)
440 elif os.path.isfile(target):
441 yield file_document(target)
442 else:
443 raise FileNotFoundError(target)
444
445
446def file_document(path: str) -> dict:
447 with open(path, "rb") as f:
448 data = f.read()
449 root = gi.tail_root(data) or gi.xml_root(data)
450 return {
451 "data": data,
452 "from_carve": False,
453 "name": os.path.basename(path),
454 "root_hint": root,
455 }
456
457
458def write_csv(path: str, rows: list) -> None:
459 fields = ["source", "offset_hex", "bytes", "chunks", "root", "category", "header", "complete",
460 "well_formed", "fragment", "tail_only", "truncated", "malformed", "element_count",
461 "max_depth", "comments", "attributes", "refs", "platform", "platform_total", "filename",
462 "parent_path", "parent_file", "xi_include", "type_attrs", "type_values", "content_values",
463 "error"]
464 with open(path, "w", newline="", encoding="utf-8") as f:
465 writer = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
466 writer.writeheader()
467 for row in rows:
468 out = dict(row)
469 out["attributes"] = " ".join(row["attributes"])
470 out["refs"] = ";".join(f"{key}={value}" for key, value in row["refs"].items())
471 out["platform"] = ";".join(f"{key}={value}" for key, value in row["platform"].items())
472 for flag in ("header", "complete", "well_formed", "fragment", "tail_only", "truncated",
473 "malformed"):
474 out[flag] = str(row[flag]).lower()
475 writer.writerow(out)
476
477
478def plural(count: int, word: str) -> str:
479 return f"{count} {word}" if count == 1 else f"{count} {word}s"
480
481
482def check_report(rows: list) -> bool:
483 """Print the validation split. Return True when no complete document is malformed."""
484 fragments = sum(1 for row in rows if row["fragment"])
485 print(f"check: {sum(1 for row in rows if row['well_formed'])} well-formed, "
486 f"{sum(1 for row in rows if row['truncated'])} truncated at the start, "
487 f"{plural(fragments, 'rootless fragment')}, "
488 f"{sum(1 for row in rows if row['malformed'])} malformed")
489 for row in rows:
490 if not (row["truncated"] or row["fragment"] or row["malformed"]):
491 continue
492 where = row["offset_hex"] or row["source"] or "?"
493 if row["malformed"]:
494 print(f" malformed {row['root'] or '?'} @ {where}: {row['error']}")
495 elif row["truncated"]:
496 print(f" truncated {row['root']} @ {where}: starts mid-document")
497 else:
498 print(f" fragment @ {where}: no root element")
499 return not any(row["malformed"] for row in rows)
500
501
502def print_summary(summary: dict, agg: dict) -> None:
503 docs = summary["documents"]
504 print(f'{docs} XML payloads, {summary["bytes"]:,} bytes '
505 f'(min {summary["min_bytes"]:,}, median {summary["median_bytes"]:,}, '
506 f'max {summary["max_bytes"]:,})')
507 print(f'{summary["well_formed"]} well-formed, {summary["tail_only"]} tail-only '
508 f'({summary["truncated"]} truncated), {plural(summary["fragments"], "rootless fragment")}, '
509 f'{summary["malformed"]} malformed')
510 print(f'{summary["root_count"]} named roots (+{summary["unattributed"]} unattributed), '
511 f'{summary["elements"]:,} elements, {summary["element_names"]:,} element names, '
512 f'{summary["attributes"]} attributes, max depth {summary["max_depth"]}, '
513 f'{summary["type_values"]} type values, {summary["content_kinds"]} content kinds')
514 print(f'{summary["comments"]} comment starts '
515 f'({summary["comments_header"]} in {summary["header_documents"]} declaration-bearing documents)')
516 refs = ", ".join(f"{key} {value:,}" for key, value in summary["references"].items())
517 platforms = ", ".join(f"{key} {value:,}" for key, value in summary["platform"].items())
518 print(f"references: {summary['platform_total']:,} platform:/ ({platforms}); {refs}")
519 print(f'include-like: {summary["filename"]:,} filename, {summary["parent_path"]} parentPath, '
520 f'{summary["parent_file"]} parentFile, {summary["xi_include"]} xi:include')
521 print("categories:")
522 for name, stats in summary["categories"].items():
523 print(f' {plural(stats["files"], "file"):8} {plural(stats["roots"], "root"):8} '
524 f'{stats["elements"]:7,} elements {name}')
525 print("roots:")
526 for root, stats in list(agg["roots"].items())[:10]:
527 if not root:
528 continue
529 print(f' {plural(stats["files"], "file"):8} {stats["elements"]:7,} elements '
530 f'{root} [{stats["category"]}]')
531
532
533def main() -> int:
534 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
535 parser.add_argument("targets", nargs="+", help="carve directory or XML file(s)")
536 parser.add_argument("--csv", help="write one row per XML document to this CSV")
537 parser.add_argument("--json", help="write the summary, per-root catalog and rows to this JSON")
538 parser.add_argument("--check", action="store_true", help="validate well-formedness and report fragments")
539 args = parser.parse_args()
540
541 rows = []
542 mode = document_mode(args.targets)
543 try:
544 for doc in load_documents(args.targets):
545 rows.append(file_row(doc, scan_xml(doc["data"])))
546 except FileNotFoundError as exc:
547 print(f"not found: {exc}", file=sys.stderr)
548 return 2
549
550 agg = aggregate(rows)
551 summary = summarize(rows, agg, mode)
552 clean = True
553 if args.check:
554 clean = check_report(rows)
555 print_summary(summary, agg)
556 if args.csv:
557 write_csv(args.csv, rows)
558 print("wrote", args.csv)
559 if args.json:
560 public_rows = [{key: value for key, value in row.items() if key != "_scan"} for row in rows]
561 with open(args.json, "w", encoding="utf-8") as f:
562 json.dump({"summary": summary, "roots": agg["roots"], "rows": public_rows}, f, indent=1)
563 print("wrote", args.json)
564 return 0 if clean else 1
565
566
567if __name__ == "__main__":
568 sys.exit(main())
diff --git a/tools/manifest.py b/tools/manifest.py
index ec8fa7427..4dd175278 100644
--- a/tools/manifest.py
+++ b/tools/manifest.py
@@ -49,7 +49,11 @@ def sha256(path: str) -> str:
49 49
50 50
51def walk(game_dir: str): 51def walk(game_dir: str):
52 for root, _, files in os.walk(game_dir): 52 def scan_failed(error: OSError) -> None:
53 raise error
54
55 # os.walk otherwise treats missing or unreadable directories as empty.
56 for root, _, files in os.walk(game_dir, onerror=scan_failed):
53 for name in sorted(files): 57 for name in sorted(files):
54 p = os.path.join(root, name) 58 p = os.path.join(root, name)
55 yield os.path.relpath(p, game_dir).replace("\\", "/"), p 59 yield os.path.relpath(p, game_dir).replace("\\", "/"), p
@@ -150,8 +154,13 @@ def main() -> int:
150 add_jobs(v) 154 add_jobs(v)
151 a = ap.parse_args() 155 a = ap.parse_args()
152 below_normal() 156 below_normal()
153 return (create(a.game_dir, a.out, a.jobs) if a.cmd == "create" 157 try:
154 else verify(a.game_dir, a.manifest, a.jobs)) 158 if a.cmd == "create":
159 return create(a.game_dir, a.out, a.jobs)
160 return verify(a.game_dir, a.manifest, a.jobs)
161 except OSError as error:
162 print(f"ERROR: {error}", file=sys.stderr)
163 return 2
155 164
156 165
157if __name__ == "__main__": 166if __name__ == "__main__":
diff --git a/tools/mc_command.py b/tools/mc_command.py
new file mode 100644
index 000000000..9f76e03b4
--- /dev/null
+++ b/tools/mc_command.py
@@ -0,0 +1,29 @@
1"""Resolve LLVM_MC to an argv list.
2
3LLVM_MC may be one executable (a path, spaces and all) or a whole command line. Windows needs the command-line
4form when llvm-mc runs inside WSL, because the official Windows LLVM build has no AMDGPU target:
5
6 set LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc
7"""
8import os
9import shlex
10
11
12def split_command(raw: str) -> list:
13 """Split a command line without eating the backslashes of a Windows path (POSIX shlex would)."""
14 raw = raw.strip()
15 if not raw:
16 return []
17 if os.path.isfile(raw):
18 return [raw] # a plain path, spaces and all
19 if os.name != "nt":
20 return shlex.split(raw)
21 parts = shlex.split(raw, posix=False)
22 return [p[1:-1] if len(p) > 1 and p[0] == p[-1] == '"' else p for p in parts]
23
24
25def mc_command(raw: str | None = None) -> list:
26 """LLVM_MC is a path, or a command line: 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'."""
27 if raw is None:
28 raw = os.environ.get("LLVM_MC", "llvm-mc")
29 return split_command(raw) or ["llvm-mc"]
diff --git a/tools/rbf0_tree.py b/tools/rbf0_tree.py
new file mode 100644
index 000000000..bea6534f7
--- /dev/null
+++ b/tools/rbf0_tree.py
@@ -0,0 +1,554 @@
1"""Decode RBF0 resources into strict JSON trees, with an optional simple XML rendering.
2
3RBF0 is RAGE's binary form of an XML data file: one record stream with an inline descriptor table. This tool reads
4inflated RBF0 resources from a carve directory or a single resource file, joins the 64 KiB continuation streams of
5one logical resource, and builds the element tree. It reports unknown descriptors, unknown record types, truncated
6payloads and structural violations as errors instead of guessing a value.
7
8The output contains names and payloads taken from the archive, so treat it as game data: keep it out of git and do
9not attach it to an issue or a pull request. Format facts and aggregate counts are in docs/rbf0.md.
10
11Usage:
12 python -I tools/rbf0_tree.py <carve-dir> <out.json> [--xml DIR] [--root NAME]... [--offset 0x...] [--limit N]
13
14The input directory holds inflated zlib streams or complete RBF0 resources. A file name that starts with a
15hexadecimal archive offset is used to order and label the resource, as in the rbf0_index.py carve layout.
16"""
17import argparse
18import collections
19import json
20import math
21import os
22import re
23import struct
24import sys
25from xml.etree import ElementTree as ET
26
27sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
28
29import rbf0_index # noqa: E402
30
31MAGIC = rbf0_index.MAGIC
32PROLOGUE = rbf0_index.PROLOGUE
33MAX_CHUNK = rbf0_index.MAX_CHUNK
34MAX_CHUNKS = rbf0_index.MAX_CHUNKS
35MAX_BYTES = rbf0_index.MAX_BYTES
36RbfError = rbf0_index.RbfError
37TYPE_NAMES = {0x00: "open", 0x10: "int", 0x20: "true", 0x30: "false", 0x40: "float",
38 0x50: "vec3", 0x60: "string"}
39VALUE_TYPES = {0x10: "int", 0x20: "bool", 0x30: "bool", 0x40: "float", 0x50: "vec3", 0x60: "string"}
40XML_BAD = re.compile(r"[^\u0009\u000a\u000d\u0020-\ud7ff\ue000-\ufffd\U00010000-\U0010ffff]")
41
42
43def _utf8(raw):
44 """Return (text, valid). Invalid bytes become U+FFFD and are counted, never silently accepted."""
45 try:
46 return raw.decode("utf-8"), True
47 except UnicodeDecodeError:
48 return raw.decode("utf-8", "replace"), False
49
50
51def _render(value):
52 """A stable textual form for XML and for JSON consumers that want one scalar spelling."""
53 if isinstance(value, bool):
54 return "true" if value else "false"
55 if isinstance(value, float):
56 if math.isnan(value):
57 return "nan"
58 if math.isinf(value):
59 return "inf" if value > 0 else "-inf"
60 return repr(value)
61 if isinstance(value, (list, tuple)):
62 return "[" + ", ".join(_render(v) for v in value) + "]"
63 return str(value)
64
65
66class TreeError(RbfError):
67 """A malformed or truncated RBF0 record stream."""
68
69
70class Parser:
71 """One RBF0 resource. `parse()` always returns a document, with a partial tree on failure."""
72
73 def __init__(self, data, source="", offset=0, chunks=1):
74 self.data = data
75 self.source = source
76 self.offset = offset
77 self.chunks = chunks
78 self.wide = data[4:8] == PROLOGUE
79 self.p = 8 if self.wide else 4
80 self.scalar = 8 if self.wide else 4
81 self.descs = []
82 self.stack = []
83 self.root = None
84 self.status = "ok"
85 self.error = ""
86 self.error_offset = None
87 self.counts = collections.Counter()
88 self.descriptor_names = set()
89 self.attribute_mismatches = 0
90 self.attribute_order_violations = 0
91 self.text_after_child = 0
92 self.text_before_child = 0
93 self.value_after_child = 0
94 self.invalid_utf8 = 0
95 self.max_depth = 0
96
97 def take(self, n, what):
98 if self.p + n > len(self.data):
99 raise TreeError(f"{what} truncated", self.p, truncated=True)
100 start = self.p
101 self.p += n
102 return self.data[start:self.p]
103
104 def _descriptor(self, index, kind, at):
105 if index == len(self.descs):
106 n = struct.unpack("<H", self.take(2, "descriptor name length"))[0]
107 raw = self.take(n, "descriptor name")
108 name, valid = _utf8(raw)
109 if not valid:
110 self.invalid_utf8 += 1
111 self.descs.append({
112 "index": index,
113 "name": name,
114 "first_type": TYPE_NAMES.get(kind, f"0x{kind:02x}"),
115 "offset": at,
116 "name_offset": self.p - n,
117 "uses": 0,
118 "types": {},
119 "utf8_valid": valid,
120 })
121 self.descriptor_names.add(name)
122 elif index > len(self.descs):
123 raise TreeError(f"descriptor index {index} of {len(self.descs)}", at)
124 desc = self.descs[index]
125 desc["uses"] += 1
126 key = TYPE_NAMES.get(kind, f"0x{kind:02x}")
127 desc["types"][key] = desc["types"].get(key, 0) + 1
128 return desc
129
130 def _attach(self, frame, node):
131 node["depth"] = frame["depth"] + 1
132 if frame["node"]["kind"] != "element":
133 raise TreeError("record outside an element", node["offset"])
134 if node["kind"] == "value" and frame["attrs_seen"] < frame["attrs_declared"]:
135 if frame["content_started"]:
136 frame["node"]["attribute_order_violation"] = True
137 self.attribute_order_violations += 1
138 frame["node"]["attributes"].append(node)
139 frame["attrs_seen"] += 1
140 return
141 if node["kind"] in ("element", "text") and frame["attrs_seen"] < frame["attrs_declared"]:
142 frame["node"]["attribute_order_violation"] = True
143 self.attribute_order_violations += 1
144 frame["content_started"] = True
145 frame["node"]["content"].append(node)
146 if node["kind"] == "element":
147 if frame["text_seen"]:
148 frame["node"]["text_before_child"] = True
149 self.text_before_child += 1
150 frame["child_seen"] = True
151 elif node["kind"] == "value":
152 if frame["child_seen"]:
153 frame["node"]["value_after_child"] = True
154 self.value_after_child += 1
155 elif node["kind"] == "text":
156 if frame["child_seen"]:
157 frame["node"]["text_after_child"] = True
158 self.text_after_child += 1
159 if frame["text_seen"]:
160 frame["node"]["multiple_text"] = True
161 frame["text_seen"] = True
162
163 def parse(self):
164 data = self.data
165 if len(data) < 4 or data[:4] != MAGIC:
166 raise TreeError("not an RBF0 stream", 0)
167 try:
168 while self.p < len(data):
169 self.record_offset = self.p
170 at = self.p
171 index = self.take(1, "record index")[0]
172 kind = self.take(1, "record type")[0]
173 if index == 0xFF:
174 if kind != 0xFF:
175 raise TreeError("close tag is not FF FF", at)
176 if not self.stack:
177 raise TreeError("close without an open element", at)
178 frame = self.stack.pop()
179 frame["node"]["end"] = self.p
180 if frame["attrs_seen"] < frame["attrs_declared"]:
181 frame["node"]["attribute_mismatch"] = True
182 self.attribute_mismatches += 1
183 if not self.stack:
184 self.root = frame["node"]
185 break
186 continue
187 if index == 0xFD:
188 if kind != 0xFF:
189 raise TreeError("text tag is not FD FF", at)
190 n = struct.unpack("<I", self.take(4, "text length"))[0]
191 raw = self.take(n, "text")
192 payload_at = self.p - n
193 body = raw[:-1] if raw.endswith(b"\x00") else raw
194 text, valid = _utf8(body)
195 if not valid:
196 self.invalid_utf8 += 1
197 node = {
198 "kind": "text",
199 "offset": at,
200 "payload_offset": payload_at,
201 "length": n,
202 "nul_terminated": raw.endswith(b"\x00"),
203 "text": text,
204 "utf8_valid": valid,
205 }
206 if not self.stack:
207 raise TreeError("text outside an element", at)
208 self._attach(self.stack[-1], node)
209 self.counts["texts"] += 1
210 continue
211 desc = self._descriptor(index, kind, at)
212 name = desc["name"]
213 if kind == 0x00:
214 raw = self.take(6, "element header")
215 payload_at = self.p - 6
216 word0, word1, attrs = struct.unpack("<HHH", raw)
217 if word0 or word1:
218 raise TreeError(f"element header word is not zero ({word0}, {word1})", at)
219 node = {
220 "kind": "element",
221 "name": name,
222 "descriptor": index,
223 "offset": at,
224 "header_offset": payload_at,
225 "attrs_declared": attrs,
226 "depth": len(self.stack) + 1,
227 "attributes": [],
228 "content": [],
229 "end": None,
230 }
231 self.counts["elements"] += 1
232 self.max_depth = max(self.max_depth, len(self.stack) + 1)
233 if self.stack:
234 self._attach(self.stack[-1], node)
235 else:
236 if self.root is not None:
237 raise TreeError("second root element", at)
238 self.root = node
239 self.stack.append({
240 "node": node,
241 "attrs_declared": attrs,
242 "attrs_seen": 0,
243 "content_started": False,
244 "child_seen": False,
245 "text_seen": False,
246 "depth": len(self.stack) + 1,
247 })
248 continue
249 if kind not in VALUE_TYPES:
250 raise TreeError(f"unknown record type {kind:#04x}", at)
251 node = self._value(kind, name, index, at)
252 if not self.stack:
253 raise TreeError("value outside an element", at)
254 self._attach(self.stack[-1], node)
255 self.counts["values"] += 1
256 except TreeError as exc:
257 if not self.error:
258 self.status = "truncated" if exc.truncated else "bad"
259 self.error = str(exc)
260 self.error_offset = exc.offset
261 if self.status == "ok":
262 if self.stack:
263 self.status = "truncated"
264 self.error = f"{len(self.stack)} unclosed element(s) at 0x{self.p:x}"
265 self.error_offset = self.p
266 elif self.root is None:
267 self.status = "bad"
268 self.error = "no root element"
269 self.error_offset = self.p
270 elif self.root.get("end") != len(data):
271 self.status = "trailing"
272 self.error = f"{len(data) - self.root['end']} bytes after the root closed"
273 self.error_offset = self.root["end"]
274 return {
275 "source": self.source,
276 "offset": self.offset,
277 "size": len(data),
278 "chunks": self.chunks,
279 "layout": "wide-64" if self.wide else "narrow-32",
280 "prologue": PROLOGUE.hex() if self.wide else "",
281 "root_name": self.root["name"] if self.root else "",
282 "status": self.status,
283 "error": self.error,
284 "error_offset": self.error_offset,
285 "end": self.root["end"] if self.root and self.root.get("end") is not None else self.p,
286 "descriptors": self.descs,
287 "descriptor_count": len(self.descs),
288 "distinct_descriptor_names": len(self.descriptor_names),
289 "counts": dict(self.counts),
290 "attribute_mismatches": self.attribute_mismatches,
291 "attribute_order_violations": self.attribute_order_violations,
292 "text_after_child": self.text_after_child,
293 "text_before_child": self.text_before_child,
294 "value_after_child": self.value_after_child,
295 "invalid_utf8": self.invalid_utf8,
296 "max_depth": self.max_depth,
297 "tree": self.root,
298 }
299
300 def _value(self, kind, name, index, at):
301 payload_at = self.p
302 extra = {}
303 if kind == 0x10:
304 raw = self.take(self.scalar, "integer")
305 value = struct.unpack("<Q" if self.wide else "<I", raw)[0]
306 self.counts["ints"] += 1
307 elif kind == 0x20 or kind == 0x30:
308 value = kind == 0x20
309 self.counts["bools"] += 1
310 elif kind == 0x40:
311 raw = self.take(self.scalar, "float")
312 value = struct.unpack("<d" if self.wide else "<f", raw)[0]
313 self.counts["floats"] += 1
314 elif kind == 0x50:
315 raw = self.take(3 * self.scalar, "vector")
316 value = list(struct.unpack("<ddd" if self.wide else "<fff", raw))
317 if any(not math.isfinite(v) for v in value):
318 extra["float_special"] = [_render(v) for v in value]
319 value = [v if math.isfinite(v) else None for v in value]
320 self.counts["vec3"] += 1
321 else: # 0x60
322 n = struct.unpack("<H", self.take(2, "string length"))[0]
323 raw = self.take(n, "string")
324 payload_at = self.p - n
325 body = raw[:-1] if raw.endswith(b"\x00") else raw
326 value, valid = _utf8(body)
327 if not valid:
328 self.invalid_utf8 += 1
329 extra = {"byte_length": n, "nul_terminated": raw.endswith(b"\x00"), "utf8_valid": valid}
330 self.counts["strings"] += 1
331 if isinstance(value, float) and not math.isfinite(value):
332 extra["float_special"] = _render(value)
333 value = None
334 return {
335 "kind": "value",
336 "name": name,
337 "descriptor": index,
338 "type": VALUE_TYPES[kind],
339 "offset": at,
340 "payload_offset": payload_at,
341 "size": self.p - payload_at,
342 "value": value,
343 **extra,
344 }
345
346
347def parse_resource(data, source="", offset=0, chunks=1):
348 """Parse one complete RBF0 resource into a tree document. A non-RBF0 magic raises; a malformed stream
349 returns a partial document with status bad or truncated."""
350 return Parser(data, source, offset, chunks).parse()
351
352
353def _rows(source):
354 """Return (rows, read) for a single resource or a directory of inflated streams/resources."""
355 if os.path.isdir(source):
356 entries = []
357 unnamed = []
358 for name in sorted(os.listdir(source)):
359 full = os.path.join(source, name)
360 if not os.path.isfile(full):
361 continue
362 with open(full, "rb") as f:
363 head = f.read(8)
364 match = re.match(r"([0-9a-fA-F]{6,})", name)
365 if match:
366 entries.append((int(match.group(1), 16), name, full, head))
367 else:
368 unnamed.append((name, full, head))
369 next_offset = max((e[0] for e in entries), default=-1) + 1
370 for name, full, head in unnamed:
371 entries.append((next_offset, name, full, head))
372 next_offset += 1
373 entries.sort(key=lambda e: e[0])
374 rows = [{"offset": off, "stored": os.path.getsize(full), "size": os.path.getsize(full),
375 "head": head, "name": name} for off, name, full, head in entries]
376 by_offset = {row["offset"]: full for row, (_, _, full, _) in zip(rows, entries)}
377
378 def read(row):
379 with open(by_offset[row["offset"]], "rb") as f:
380 return f.read()
381 return rows, read
382 with open(source, "rb") as f:
383 data = f.read()
384 row = {"offset": 0, "stored": len(data), "size": len(data), "head": data[:8],
385 "name": os.path.basename(source)}
386 return [row], lambda _row: data
387
388
389def decode_source(source, roots=None, offset=None, limit=None, progress=None):
390 """Decode every RBF0 start in `source`, joining 64 KiB continuations. Returns (docs, summary)."""
391 rows, read = _rows(source)
392 starts = [i for i, row in enumerate(rows) if row["head"][:4] == MAGIC]
393 if offset is not None:
394 starts = [i for i in starts if rows[i]["offset"] == offset]
395 if not starts:
396 raise SystemExit(f"no RBF0 resource at offset 0x{offset:x}")
397 wanted = set(roots or ())
398 docs = []
399 for i in starts:
400 blob = read(rows[i])
401 chunks = 1
402 doc = parse_resource(blob, rows[i]["name"], rows[i]["offset"], chunks)
403 while (doc["status"] == "truncated" and chunks < MAX_CHUNKS and len(blob) < MAX_BYTES
404 and rows[i + chunks - 1]["size"] == MAX_CHUNK and i + chunks < len(rows)):
405 nxt = rows[i + chunks]
406 if nxt["head"][:4] in (MAGIC, b"PSIN"):
407 break
408 blob += read(nxt)
409 chunks += 1
410 doc = parse_resource(blob, rows[i]["name"], rows[i]["offset"], chunks)
411 if doc["status"] != "truncated":
412 break
413 if wanted and doc["root_name"] not in wanted:
414 continue
415 docs.append(doc)
416 if limit is not None and len(docs) >= limit:
417 break
418 if progress:
419 progress(len(docs), len(starts))
420 summary = _summary(docs)
421 summary["source"] = os.path.abspath(source)
422 return docs, summary
423
424
425def _summary(docs):
426 roots = collections.Counter(d["root_name"] for d in docs)
427 layouts = collections.Counter(d["layout"] for d in docs)
428 status = collections.Counter(d["status"] for d in docs)
429 counts = collections.Counter()
430 for d in docs:
431 counts.update(d["counts"])
432 return {
433 "resources": len(docs),
434 "ok": status.get("ok", 0),
435 "bad": status.get("bad", 0),
436 "truncated": status.get("truncated", 0),
437 "trailing": status.get("trailing", 0),
438 "layouts": dict(layouts),
439 "roots": dict(roots),
440 "descriptors": sum(d["descriptor_count"] for d in docs),
441 "distinct_descriptor_names": len({x["name"] for d in docs for x in d["descriptors"]}),
442 "elements": counts.get("elements", 0),
443 "values": counts.get("values", 0),
444 "texts": counts.get("texts", 0),
445 "strings": counts.get("strings", 0),
446 "ints": counts.get("ints", 0),
447 "floats": counts.get("floats", 0),
448 "bools": counts.get("bools", 0),
449 "vec3": counts.get("vec3", 0),
450 "max_depth": max((d["max_depth"] for d in docs), default=0),
451 "attribute_mismatches": sum(d["attribute_mismatches"] for d in docs),
452 "attribute_order_violations": sum(d["attribute_order_violations"] for d in docs),
453 "text_after_child": sum(d["text_after_child"] for d in docs),
454 "value_after_child": sum(d["value_after_child"] for d in docs),
455 "invalid_utf8": sum(d["invalid_utf8"] for d in docs),
456 "status": dict(status),
457 }
458
459
460def _xml_safe(text):
461 return XML_BAD.sub("\ufffd", text)
462
463
464def _xml_node(parent, node, tag=None):
465 if node["kind"] == "element":
466 attrs = {"name": _xml_safe(node["name"]), "descriptor": str(node["descriptor"]),
467 "offset": f"0x{node['offset']:x}", "attrs": str(node["attrs_declared"])}
468 if node.get("end") is not None:
469 attrs["end"] = f"0x{node['end']:x}"
470 el = ET.SubElement(parent, "node", attrs)
471 for value in node["attributes"]:
472 _xml_node(el, value, "attr")
473 for child in node["content"]:
474 _xml_node(el, child)
475 return el
476 tag = tag or ("text" if node["kind"] == "text" else "value")
477 attrs = {"offset": f"0x{node['offset']:x}"}
478 if node["kind"] == "value":
479 attrs.update({"name": _xml_safe(node["name"]), "descriptor": str(node["descriptor"]),
480 "type": node["type"]})
481 if node.get("float_special") is not None:
482 text = _render(node["float_special"])
483 else:
484 text = _render(node["value"])
485 else:
486 attrs["length"] = str(node["length"])
487 text = node["text"]
488 if node.get("utf8_valid") is False:
489 attrs["utf8"] = "invalid"
490 el = ET.SubElement(parent, tag, attrs)
491 el.text = _xml_safe(text)
492 return el
493
494
495def write_xml(directory, docs):
496 """Write one generic XML file per resource. Element names are fixed, so any descriptor name is safe."""
497 os.makedirs(directory, exist_ok=True)
498 paths = []
499 for i, doc in enumerate(docs):
500 root = ET.Element("rbf0", {
501 "root": _xml_safe(doc["root_name"]), "layout": doc["layout"],
502 "offset": f"0x{doc['offset']:x}",
503 "size": str(doc["size"]), "descriptors": str(doc["descriptor_count"]),
504 "status": doc["status"]})
505 if doc["tree"] is not None:
506 _xml_node(root, doc["tree"])
507 tree = ET.ElementTree(root)
508 ET.indent(tree, space=" ")
509 name = f"{doc['offset']:08x}.xml"
510 path = os.path.join(directory, name)
511 if os.path.exists(path):
512 path = os.path.join(directory, f"{doc['offset']:08x}-{i:04d}.xml")
513 tree.write(path, encoding="utf-8", xml_declaration=True)
514 paths.append(path)
515 return paths
516
517
518def write_json(path, docs, summary):
519 with open(path, "w", encoding="utf-8") as f:
520 json.dump({"tool": "rbf0_tree", "format": 1, "summary": summary, "resources": docs},
521 f, indent=1, ensure_ascii=False, allow_nan=False)
522
523
524def main(argv=None):
525 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
526 ap.add_argument("source", help="a carve directory, a complete resource, or a single RBF0 stream")
527 ap.add_argument("out", help="JSON output path")
528 ap.add_argument("--xml", metavar="DIR", help="also write one generic XML file per resource into DIR")
529 ap.add_argument("--root", action="append", metavar="NAME", help="keep only this root schema (repeatable)")
530 ap.add_argument("--offset", type=lambda s: int(s, 0), help="decode only the resource at this archive offset")
531 ap.add_argument("--limit", type=int, help="stop after this many selected resources")
532 ap.add_argument("--quiet", action="store_true")
533 args = ap.parse_args(argv)
534
535 def progress(n, total):
536 if not args.quiet and (n % 100 == 0 or n == total):
537 print(f"[{n}/{total}] resources", flush=True)
538
539 docs, summary = decode_source(args.source, roots=args.root, offset=args.offset,
540 limit=args.limit, progress=progress)
541 write_json(args.out, docs, summary)
542 paths = write_xml(args.xml, docs) if args.xml else []
543 if not args.quiet:
544 print(f"{summary['resources']} resources: {summary['ok']} ok, {summary['bad']} bad, "
545 f"{summary['truncated']} truncated, {summary['trailing']} trailing")
546 print(f"{summary['elements']} elements, {summary['texts']} texts, {summary['strings']} strings, "
547 f"{summary['descriptors']} descriptors -> {args.out}")
548 if paths:
549 print(f"{len(paths)} XML files -> {args.xml}")
550 return 0 if summary["ok"] == summary["resources"] else 1
551
552
553if __name__ == "__main__":
554 sys.exit(main())
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index 819eb0aad..5201fa31d 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -3413,7 +3413,14 @@ class Gen:
3413 """s_load_dwordxN sD, s[p:p+1], off -> N dwords at (64-bit pointer + off) 3413 """s_load_dwordxN sD, s[p:p+1], off -> N dwords at (64-bit pointer + off)
3414 s_buffer_load_dwordxN sD, s[v:v+3], off -> N dwords at (V# base address + off) 3414 s_buffer_load_dwordxN sD, s[v:v+3], off -> N dwords at (V# base address + off)
3415 Both become PhysicalStorageBuffer loads (Vulkan buffer device address). V# base = dword0 | (dword1 & 0xFFFF) << 32 3415 Both become PhysicalStorageBuffer loads (Vulkan buffer device address). V# base = dword0 | (dword1 & 0xFFFF) << 32
3416 (AMD RDNA ISA, buffer resource descriptor).""" 3416 (AMD RDNA ISA, buffer resource descriptor).
3417 off is an immediate or a scalar register. An SMEM load can carry both, which llvm-mc prints as
3418 "sOFF offset:IMM" (the immediate arrives in mods); the address is then base + sOFF + IMM. Measured on an
3419 RX 6800 (gfx1030) for s_buffer_load_dword/x2/x4/x8: soffset 8 + imm 4 reads +12. s_load_dword* shares the
3420 encoding and gets the same rule (not measured). The immediate is zero-extended from 32 bits exactly as the
3421 immediate-only form is.
3422 Not modelled: for s_buffer_load* the hardware was measured to truncate base, sOFF and IMM each to a multiple
3423 of 4 and to return 0 past num_records (docs/design.md, Scalar/buffer memory)."""
3417 n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) 3424 n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1])
3418 d, base = a[0], a[1] 3425 d, base = a[0], a[1]
3419 # A single dword may also land in vcc_lo / m0 / vcc_hi (seen: s_buffer_load_dword vcc_lo, ...). 3426 # A single dword may also land in vcc_lo / m0 / vcc_hi (seen: s_buffer_load_dword vcc_lo, ...).
@@ -3432,6 +3439,15 @@ class Gen:
3432 if base.get("n") != 2: 3439 if base.get("n") != 2:
3433 raise Unsupported("s_load without 64-bit pointer") 3440 raise Unsupported("s_load without 64-bit pointer")
3434 off = a[2] if len(a) > 2 else {"k": "imm", "v": 0} 3441 off = a[2] if len(a) > 2 else {"k": "imm", "v": 0}
3442 inst = [m.split(":", 1)[1] for m in mods if m.startswith("offset:")]
3443 if len(a) > 3 or len(inst) > 1 or (inst and off["k"] == "imm"):
3444 raise Unsupported(f"{op} offset form") # not something llvm-mc prints: don't guess an address
3445 imm = None
3446 if inst:
3447 try:
3448 imm = int(inst[0], 0)
3449 except ValueError:
3450 raise Unsupported(f"{op} offset:{inst[0]}") from None
3435 offv = self.src_u(off) 3451 offv = self.src_u(off)
3436 l64, h64, sh, addr, o64, full = (self.tmp() for _ in range(6)) 3452 l64, h64, sh, addr, o64, full = (self.tmp() for _ in range(6))
3437 self.emit(f"{l64} = OpUConvert %ulong {lo}") 3453 self.emit(f"{l64} = OpUConvert %ulong {lo}")
@@ -3440,6 +3456,11 @@ class Gen:
3440 self.emit(f"{addr} = OpBitwiseOr %ulong {sh} {l64}") 3456 self.emit(f"{addr} = OpBitwiseOr %ulong {sh} {l64}")
3441 self.emit(f"{o64} = OpUConvert %ulong {offv}") 3457 self.emit(f"{o64} = OpUConvert %ulong {offv}")
3442 self.emit(f"{full} = OpIAdd %ulong {addr} {o64}") 3458 self.emit(f"{full} = OpIAdd %ulong {addr} {o64}")
3459 if imm is not None: # register offset and immediate: both are added
3460 i64, both = self.tmp(), self.tmp()
3461 self.emit(f"{i64} = OpUConvert %ulong {self.cu(imm)}")
3462 self.emit(f"{both} = OpIAdd %ulong {full} {i64}")
3463 full = both
3443 ptr = self.tmp() 3464 ptr = self.tmp()
3444 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") 3465 self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}")
3445 self.uses_psb = True 3466 self.uses_psb = True
@@ -5648,7 +5669,7 @@ def pos_export_layout(osg1, insns):
5648 - clip distances precede cull distances, packed contiguously into 4-component pos exports (<= 8 total). 5669 - clip distances precede cull distances, packed contiguously into 4-component pos exports (<= 8 total).
5649 Contrasted with DXBC OSG1 (D3D_NAME: 2=SV_ClipDistance, 3=SV_CullDistance, 5670 Contrasted with DXBC OSG1 (D3D_NAME: 2=SV_ClipDistance, 3=SV_CullDistance,
5650 4=SV_RenderTargetArrayIndex, 5=SV_ViewportArrayIndex, 23=SV_ShadingRate). 5671 4=SV_RenderTargetArrayIndex, 5=SV_ViewportArrayIndex, 23=SV_ShadingRate).
5651 When OSG1 is absent, infer contiguous ClipDistance slots from non-off pos1..pos2 exports. 5672 When OSG1 is absent (or declares no clip/cull/misc outputs), pos1..pos3 exports are ignored.
5652 """ 5673 """
5653 misc_svs = {sv for _, _, sv, _, _ in osg1 if sv in (4, 5, 23)} 5674 misc_svs = {sv for _, _, sv, _, _ in osg1 if sv in (4, 5, 23)}
5654 has_misc = bool(misc_svs) 5675 has_misc = bool(misc_svs)
@@ -5667,21 +5688,6 @@ def pos_export_layout(osg1, insns):
5667 if (mask >> c) & 1: 5688 if (mask >> c) & 1:
5668 slots.append(("cull", cull_n)) 5689 slots.append(("cull", cull_n))
5669 cull_n += 1 5690 cull_n += 1
5670 if not osg1:
5671 used = set()
5672 for ins in insns:
5673 if base_op(ins["op"]) != "exp":
5674 continue
5675 a = ins["args"]
5676 tgt = a[0]["t"] if a and a[0]["k"] in ("target", "special") else ""
5677 if tgt in ("pos1", "pos2"):
5678 p = int(tgt[3:])
5679 for c, x in enumerate(a[1:5]):
5680 if not (x["k"] == "special" and x["t"] == "off"):
5681 used.add((p - 1) * 4 + c)
5682 if used:
5683 clip_n = min(max(used) + 1, 8)
5684 slots = [("clip", i) for i in range(clip_n)]
5685 base_pos = 2 if has_misc else 1 5691 base_pos = 2 if has_misc else 1
5686 pos_map = {} 5692 pos_map = {}
5687 for k, target in enumerate(slots[:8]): 5693 for k, target in enumerate(slots[:8]):
diff --git a/tools/root_sig_contract.py b/tools/root_sig_contract.py
new file mode 100644
index 000000000..e1a46ae86
--- /dev/null
+++ b/tools/root_sig_contract.py
@@ -0,0 +1,155 @@
1r"""Reconcile a root signature against the translator's user-SGPR reads (stdlib only).
2
3A shader is identified by its index.json entry (user_sgpr_reads from
4tools/shader_meta.py); the candidate root signature is a hand-written JSON
5file in this tool's format (see --example), never game data.
6
7Usage:
8 python -I tools/root_sig_contract.py <index.json> --rootsig <sig.json>
9 python -I tools/root_sig_contract.py <index.json> --rootsig <sig.json> --cluster
10 python -I tools/root_sig_contract.py --example
11
12Exit code is 0 when every read is compatible, 1 on the first contradiction
13(hard fail: a mismatch means every draw/dispatch with that pair is corrupt).
14"""
15import argparse
16import json
17import sys
18
19# Packing order mirrors runtime/src/root_signature.{h,cpp}: constants take
20# NumValues dwords, root descriptors and tables take 2 (VA lo/hi), static
21# samplers take none.
22KIND_TO_TYPES = {
23 "const32": {"constants"},
24 "ptr64_lo": {"descriptor", "table"},
25 "ptr64_hi": {"descriptor", "table"},
26 "ptr32_lo": {"descriptor", "table"},
27 "vsharp": {"descriptor", "table"},
28 "tsharp": {"descriptor", "table"},
29 "ssharp": {"descriptor", "table"},
30}
31
32
33def pack_layout(sig):
34 """Lay out root params into 32 dwords. Returns (dwords, error).
35
36 dwords[i] = {"param": index, "sub": sub-dword, "ptype": ptype}.
37 error is set (and dwords empty) on spill, cost overflow or bad input:
38 refuse, never truncate.
39 """
40 dwords = []
41 cost = 0
42 params = [dict(p) for p in sig.get("params", [])] # normalized copy; input untouched
43 if len(params) > 64:
44 return [], "more than 64 root parameters"
45 for index, p in enumerate(params):
46 ptype = p.get("type", "")
47 if ptype == "constants":
48 count = p.get("count", 0)
49 if not isinstance(count, int) or count < 1:
50 return [], f"param {index}: constants need count >= 1"
51 width, cost_add = count, count
52 elif ptype in ("cbv", "srv", "uav"):
53 width, cost_add = 2, 2
54 ptype = "descriptor"
55 elif ptype == "table":
56 width, cost_add = 2, 1
57 else:
58 return [], f"param {index}: unknown type {ptype!r}"
59 cost += cost_add
60 if cost > 64:
61 return [], "exceeds the 64-dword D3D12 cost limit"
62 if len(dwords) + width > 32:
63 return [], "needs more than 32 user SGPRs (spill unsupported)"
64 for sub in range(width):
65 dwords.append({"param": index, "sub": sub, "ptype": ptype})
66 return dwords, ""
67
68
69def reconcile(shader_reads, dwords):
70 """Check one shader's reads against the packed layout.
71
72 Returns a list of contradiction strings (empty = compatible).
73 """
74 issues = []
75 by_sgpr = {}
76 for read in shader_reads:
77 by_sgpr.setdefault(read["sgpr"], []).append(read["kind"])
78 for sgpr in sorted(by_sgpr):
79 kinds = by_sgpr[sgpr]
80 if sgpr >= len(dwords):
81 issues.append(f"s{sgpr} read but layout has {len(dwords)} dwords")
82 continue
83 slot = dwords[sgpr]
84 for kind in kinds:
85 allowed = KIND_TO_TYPES.get(kind)
86 if allowed is None:
87 issues.append(f"s{sgpr}: unknown read kind {kind!r}")
88 elif slot["ptype"] not in allowed:
89 issues.append(
90 f"s{sgpr} ({kind}) incompatible with param "
91 f"{slot['param']} ({slot['ptype']})")
92 if kind == "ptr64_hi":
93 lo = dwords[sgpr - 1] if sgpr > 0 else None
94 if slot["sub"] != 1 or lo is None or lo["param"] != slot["param"] \
95 or lo["sub"] != 0:
96 issues.append(f"s{sgpr} (ptr64_hi) without paired lo dword")
97 return issues
98
99
100def cluster(shaders):
101 """Group shaders by read-set shape. Returns [(shape, count, names)]."""
102 groups = {}
103 for name, entry in shaders.items():
104 reads = entry.get("user_sgpr_reads", [])
105 shape = tuple(sorted((r["sgpr"], r["kind"]) for r in reads))
106 groups.setdefault(shape, []).append(name)
107 ranked = sorted(groups.items(), key=lambda kv: -len(kv[1]))
108 return [(shape, len(names), names) for shape, names in ranked]
109
110
111def main():
112 ap = argparse.ArgumentParser(description="Root-signature vs shader-reads reconciler.")
113 ap.add_argument("index", nargs="?", help="spirv/index.json")
114 ap.add_argument("--rootsig", default=None, help="hand-written root-signature JSON")
115 ap.add_argument("--cluster", action="store_true", help="print read-set shape clustering")
116 ap.add_argument("--example", action="store_true", help="print an empty hand-written sig template")
117 a = ap.parse_args()
118 if a.example:
119 print(json.dumps({"version": "1.1", "flags": 0, "params": [
120 {"type": "constants", "count": 4, "visibility": "all"},
121 {"type": "cbv", "visibility": "vertex"},
122 {"type": "table", "ranges": [{"kind": "srv", "count": 8}],
123 "visibility": "pixel"}],
124 "static_samplers": []}, indent=2))
125 return 0
126 if not a.index or not a.rootsig:
127 ap.error("index.json and --rootsig are required (or --example)")
128 with open(a.index, encoding="utf-8") as f:
129 index = json.load(f)
130 with open(a.rootsig, encoding="utf-8") as f:
131 sig = json.load(f)
132 dwords, error = pack_layout(sig)
133 if error:
134 print(f"root signature refused: {error}")
135 return 1
136 print(f"packed {len(dwords)} dwords from {len(sig.get('params', []))} params")
137 bad = 0
138 for name in sorted(index):
139 reads = index[name].get("user_sgpr_reads", [])
140 issues = reconcile(reads, dwords)
141 if issues:
142 bad += 1
143 print(f"CONTRADICTION {name}:")
144 for issue in issues:
145 print(f" - {issue}")
146 if a.cluster:
147 print("read-set shapes (shape -> shaders):")
148 for shape, count, names in cluster(index)[:20]:
149 print(f" {count:6} {shape} e.g. {names[0]}")
150 print(f"{len(index)} shaders: {len(index) - bad} compatible, {bad} contradictory")
151 return 1 if bad else 0
152
153
154if __name__ == "__main__":
155 sys.exit(main())
diff --git a/tools/rpf9_carve.py b/tools/rpf9_carve.py
index be24299ff..871e7f610 100644
--- a/tools/rpf9_carve.py
+++ b/tools/rpf9_carve.py
@@ -51,6 +51,9 @@ def main() -> int:
51 break 51 break
52 s = mt.start() 52 s = mt.start()
53 if m[s:s + 3] == b"KB2": 53 if m[s:s + 3] == b"KB2":
54 if s + 0x1C > size: # header cut off by the end of the file (a truncated copy): not a video
55 pos = s + 1
56 continue
54 blen = struct.unpack_from("<I", m, s + 4)[0] + 8 57 blen = struct.unpack_from("<I", m, s + 4)[0] + 8
55 w, h = struct.unpack_from("<II", m, s + 0x14) 58 w, h = struct.unpack_from("<II", m, s + 0x14)
56 if not (64 <= blen <= size - s and 16 <= w <= 8192 and 16 <= h <= 8192): 59 if not (64 <= blen <= size - s and 16 <= w <= 8192 and 16 <= h <= 8192):
@@ -117,6 +120,7 @@ def main() -> int:
117 with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8") as f: 120 with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8") as f:
118 json.dump({"summary": summary, "files": rows}, f) 121 json.dump({"summary": summary, "files": rows}, f)
119 print(json.dumps(summary, indent=1)) 122 print(json.dumps(summary, indent=1))
123 span = max(1, span) # an empty data area (or --start at the end) has nothing to divide by
120 print(f"readable: {total / span:.1%}, zero padding {zero / span:.1%}, unread {unread / span:.1%}") 124 print(f"readable: {total / span:.1%}, zero padding {zero / span:.1%}, unread {unread / span:.1%}")
121 return 0 125 return 0
122 126
diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py
index 942d44dac..5923ee66c 100644
--- a/tools/shader_disasm.py
+++ b/tools/shader_disasm.py
@@ -13,34 +13,20 @@ Set LLVM_MC to llvm-mc's path, or to a whole command such as
13""" 13"""
14import argparse 14import argparse
15import os 15import os
16import shlex
17import struct 16import struct
18import subprocess 17import subprocess
19import sys 18import sys
20from concurrent.futures import ThreadPoolExecutor 19from concurrent.futures import ThreadPoolExecutor
21 20
21sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
22from mc_command import mc_command # noqa: E402
23
22TRIPLE = "amdgcn--amdpal" 24TRIPLE = "amdgcn--amdpal"
23ENDPGM = b"\x00\x00\x81\xbf" 25ENDPGM = b"\x00\x00\x81\xbf"
24PROBE = "0x00 0x00 0x81 0xbf" # s_endpgm: the one instruction every shader ends with 26PROBE = "0x00 0x00 0x81 0xbf" # s_endpgm: the one instruction every shader ends with
25FAILED = [] # (path, first stderr line) for shaders that produced no disassembly 27FAILED = [] # (path, first stderr line) for shaders that produced no disassembly
26 28
27 29
28def split_command(raw: str) -> list:
29 """Split LLVM_MC without eating the backslashes of a Windows path (POSIX shlex would)."""
30 if os.name != "nt":
31 return shlex.split(raw)
32 parts = shlex.split(raw, posix=False)
33 return [p[1:-1] if len(p) > 1 and p[0] == p[-1] == '"' else p for p in parts]
34
35
36def mc_command() -> list:
37 """LLVM_MC is a path, or a command line: 'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc'."""
38 raw = os.environ.get("LLVM_MC", "llvm-mc").strip()
39 if os.path.isfile(raw):
40 return [raw] # a plain path, spaces and all
41 return split_command(raw) or ["llvm-mc"]
42
43
44MC = mc_command() 30MC = mc_command()
45 31
46 32
@@ -56,13 +42,15 @@ def probe(mcpu: str) -> None:
56 input=PROBE, capture_output=True, text=True, 42 input=PROBE, capture_output=True, text=True,
57 creationflags=getattr(subprocess, "BELOW_NORMAL_PRIORITY_CLASS", 0)) 43 creationflags=getattr(subprocess, "BELOW_NORMAL_PRIORITY_CLASS", 0))
58 except OSError as e: 44 except OSError as e:
59 fail(f"'{MC[0]}' could not be started: {e}. Put llvm-mc on PATH or set LLVM_MC to it, e.g.\n" 45 fail(f"'{MC[0]}' could not be started: {e}. Put llvm-mc on PATH or set LLVM_MC to it (on Windows,\n"
46 f"scripts\\build_llvm_mc.ps1 builds one and sets it), e.g.\n"
60 f" LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc") 47 f" LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc")
61 if p.returncode != 0 or "s_endpgm" not in p.stdout: 48 if p.returncode != 0 or "s_endpgm" not in p.stdout:
62 why = (p.stderr.strip().splitlines() or [f"exit code {p.returncode}"])[0] 49 why = (p.stderr.strip().splitlines() or [f"exit code {p.returncode}"])[0]
63 fail(f"'{' '.join(MC)}' did not disassemble an s_endpgm: {why}\n" 50 fail(f"'{' '.join(MC)}' did not disassemble an s_endpgm: {why}\n"
64 f"The disassembler needs LLVM 21+ with the AMDGPU target. The official Windows LLVM build has no\n" 51 f"The disassembler needs LLVM 21+ with the AMDGPU target. The official Windows LLVM build has no\n"
65 f"AMDGPU target; run it from WSL instead (docs/design.md, 'Disassembling shaders'), e.g.\n" 52 f"AMDGPU target: build a native one with scripts\\build_llvm_mc.ps1, or run it from WSL\n"
53 f"(docs/design.md, 'Disassembling shaders'), e.g.\n"
66 f" LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc") 54 f" LLVM_MC=wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc")
67 55
68 56
diff --git a/tools/ttpf_mips.py b/tools/ttpf_mips.py
new file mode 100644
index 000000000..050eb9b22
--- /dev/null
+++ b/tools/ttpf_mips.py
@@ -0,0 +1,845 @@
1"""Measure and decode the TTPF (RDS5) compact mip chain, including the packed tail.
2
3The compact profile in `TtpfReader` is the AMD Gfx10 mip-tail layout: mips smaller
4than half a tile share one tile at offset 0, and the rest are standalone, smallest
5first. `TtpfReader` only trusts a hand-validated tuple table and stops at the
6descriptor's `nonTail` field, which is not the layout boundary. This tool computes
7the layout from the descriptor and validates it against the native allocation span,
8then decodes the mips that are zlib/raw (no BCPack backend is used or guessed).
9
10Read-only: no texture bytes are printed or committed. `scan` emits aggregate
11counters only. `layout` prints descriptor fields and offsets. `check` prints the
12BC block-average error against a 2x2 downsample of the parent mip; it decodes
13BC1, BC3, BC4_UNORM and BC5_UNORM (BC2, the SNORM BC4/5 variants, BC6H and BC7
14are sized but not decoded, and uncompressed tiling is not validated). `export`
15writes a full BC chain only when every source mip is zlib/raw.
16
17 python -I tools/ttpf_mips.py scan <game root or pool paths...> [--json out]
18 python -I tools/ttpf_mips.py layout <pool.ttpf> <index>
19 python -I tools/ttpf_mips.py check <pool.ttpf> <index>
20 python -I tools/ttpf_mips.py export <pool.ttpf> <index> <out.dds> [--mips N] [--force]
21
22Standard library only. The RDS5/ETPF checks mirror rpf9-explorer's `TtpfReader`
23(MIT); the tile patterns and tail formula are the AMD Gfx10 4 KiB/64 KiB layouts
24already used by that reader and recorded in docs/textures.md.
25"""
26import argparse
27import glob
28import json
29import mmap
30import os
31import struct
32import sys
33import zlib
34
35MAX_OUTPUT = 256 * 1024 * 1024
36MAX_TEXTURES = 250_000
37ETPF_VERSION = 634
38
39# DXGI format -> element bytes, as RageTextureDecoder.ElementBytes. DXGI 11
40# (R16G16B16A16_UNORM) is 8 bytes but is left out here as well: its uncompressed
41# tiling has not been validated, so `scan` reports it as a format gap.
42ELEMENT_BYTES = {
43 2: 16, 3: 16, 4: 16, 6: 12, 7: 12, 8: 12, 10: 8, 12: 8, 13: 8, 14: 8,
44 16: 8, 17: 8, 18: 8, 24: 4, 25: 4, 26: 4, 28: 4, 29: 4, 30: 4, 31: 4, 32: 4,
45 34: 4, 35: 4, 36: 4, 37: 4, 38: 4, 41: 4, 42: 4, 43: 4, 49: 2, 50: 2, 51: 2,
46 52: 2, 54: 2, 56: 2, 57: 2, 58: 2, 59: 2, 61: 1, 62: 1, 63: 1, 64: 1, 65: 1,
47 71: 8, 72: 8, 74: 16, 75: 16, 77: 16, 78: 16, 80: 8, 81: 8, 83: 16, 84: 16,
48 87: 4, 88: 4, 91: 4, 93: 4, 95: 16, 96: 16, 98: 16, 99: 16,
49}
50BC_FORMATS = frozenset(range(70, 85)) | frozenset(range(94, 100))
51
52# AMD Gfx10 intra-tile bit order (bit index -> source bit), from TtpfReader.
53PATTERNS_4K = {
54 0: (1, 2, 3, 4, -1, -2, -3, -4, -5, 5, -6, 6),
55 1: (0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6),
56 2: (0, 0, 1, 2, -1, -2, -3, 3, -4, 4, -5, 5),
57 3: (0, 0, 0, 1, -1, -2, 2, 3, -3, 4, -4, 5),
58 4: (0, 0, 0, 0, -1, -2, 1, 2, -3, 3, -4, 4),
59}
60PATTERNS_64K = {
61 0: (1, 2, 3, -2, -1, -3, 4, -4, -5, 5, -6, 6, -7, 7, -8, 8),
62 1: (0, 1, 2, 3, -1, -2, -3, 4, -4, 5, -5, 6, -6, 7, -7, 8),
63 2: (0, 0, 1, 2, -1, -2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7),
64 3: (0, 0, 0, 1, -1, 2, 3, -2, -3, 4, -4, 5, -5, 6, -6, 7),
65 4: (0, 0, 0, 0, 1, -1, 2, -2, -3, 3, -4, 4, -5, 5, -6, 6),
66}
67
68# The profile tuples `TtpfReader.ValidatedCompactProfile` accepts. Reproduced only
69# so `scan` can show the reader's published skip/partial split next to the layout
70# result; decoding does not depend on this table.
71VALIDATED_COMPACT = {
72 (4, 1024, 1024, 9, 3, 8, 0x503, 0x00B00106),
73 (6, 512, 512, 8, 3, 8, 0x041, 0x00B800D4),
74 (4, 256, 256, 7, 1, 8, 0x103, 0),
75 (4, 512, 512, 8, 3, 16, 0x482, 0x015000F5),
76 (4, 1024, 512, 8, 3, 8, 0x482, 0x015000F5),
77 (4, 512, 1024, 8, 3, 8, 0x483, 0x013000F5),
78 (4, 128, 256, 6, 1, 8, 0x083, 0),
79 (4, 256, 512, 7, 1, 8, 0x167, 0),
80 (4, 512, 256, 7, 1, 8, 0x166, 0),
81 (4, 256, 256, 7, 1, 16, 0x166, 0),
82 (4, 1024, 512, 8, 3, 16, 0x504, 0x900106),
83 (4, 1024, 256, 7, 3, 16, 0x484, 0x11000F5),
84 (6, 1024, 256, 7, 3, 8, 0x42, 0x9800D4),
85 (6, 64, 1024, 5, 3, 8, 0x83, 0x3800B4),
86 (4, 512, 1024, 8, 3, 16, 0x503, 0xB00106),
87 (4, 512, 128, 6, 1, 16, 0x168, 0),
88 (6, 256, 1024, 7, 3, 8, 0x83, 0x3800D4),
89 (4, 1024, 128, 6, 1, 8, 0x168, 0),
90 (4, 2048, 256, 7, 3, 16, 0x508, 0x100106),
91 (4, 2048, 512, 8, 3, 8, 0x504, 0x900106),
92 (6, 512, 256, 7, 3, 16, 0x42, 0x9800D4),
93 (6, 1024, 128, 6, 3, 16, 0x84, 0x1800D4),
94 (4, 512, 128, 6, 1, 8, 0x104, 0),
95 (4, 256, 1024, 7, 3, 16, 0x483, 0x13000F5),
96 (6, 1024, 64, 5, 3, 16, 0x83, 0x3800B4),
97 (6, 256, 512, 7, 3, 16, 0x41, 0xB800D4),
98 (4, 128, 128, 6, 1, 16, 0x82, 0),
99 (4, 512, 64, 5, 1, 16, 0x108, 0),
100 (4, 256, 128, 6, 1, 16, 0x104, 0),
101 (6, 128, 1024, 6, 3, 16, 0x83, 0x3800D4),
102 (4, 512, 64, 5, 1, 8, 0x84, 0),
103 (4, 128, 512, 6, 1, 16, 0x167, 0),
104 (4, 256, 128, 6, 1, 8, 0x82, 0),
105 (4, 1024, 64, 5, 1, 8, 0x108, 0),
106 (6, 1024, 32, 4, 3, 16, 0x82, 0x5800B4),
107 (4, 128, 512, 6, 1, 8, 0x107, 0),
108 (4, 512, 2048, 8, 3, 8, 0x507, 0x300106),
109 (4, 256, 2048, 7, 3, 8, 0x507, 0x3000F5),
110 (4, 512, 32, 4, 1, 16, 0x107, 0),
111 (6, 128, 1024, 6, 3, 8, 0x83, 0x3800B4),
112 (6, 64, 1024, 5, 3, 16, 0x83, 0x3800B4),
113 (4, 256, 256, 5, 1, 16, 0x166, 0),
114 (4, 128, 256, 6, 1, 16, 0x103, 0),
115 (4, 256, 64, 5, 1, 16, 0x84, 0),
116 (4, 16, 256, 3, 1, 16, 0x83, 0),
117 (4, 256, 32, 4, 1, 16, 0x84, 0),
118 (4, 64, 512, 5, 1, 16, 0x107, 0),
119 (4, 2048, 256, 7, 3, 8, 0x484, 0x11000F5),
120 (4, 64, 512, 5, 1, 8, 0x107, 0),
121 (4, 64, 256, 5, 1, 8, 0x83, 0),
122 (6, 256, 512, 9, 3, 16, 0x41, 0xB800D4),
123 (6, 32, 1024, 4, 3, 16, 0x82, 0x5800B4),
124 (4, 512, 512, 3, 3, 8, 0x502, 0xD00006),
125 (36, 1024, 1024, 9, 3, 8, 0x503, 0xB00106),
126 (36, 256, 256, 7, 1, 8, 0x103, 0),
127}
128VALIDATED_AUX = dict(mips=3, non_tail=3, meta=0x1A8, extra=0x01080008, width=1024,
129 height_a=512, fmt_a=61, height_b=1024, bytes_b=8)
130
131
132class LayoutError(ValueError):
133 pass
134
135
136class BcpackRequired(NotImplementedError):
137 pass
138
139
140def u32(b, o):
141 return struct.unpack_from("<I", b, o)[0]
142
143
144def u64(b, o):
145 return struct.unpack_from("<Q", b, o)[0]
146
147
148def align(v, n):
149 return (v + n - 1) // n * n
150
151
152def tile_mode(mode):
153 """Descriptor mode is a flag bit plus a 4-bit Gfx10 tile mode at bit 1."""
154 return (mode >> 1) & 0xF
155
156
157def tile_bytes(mode):
158 # Tile mode 0 is SW_64KB_D; 1-3 are SW_4KB_S; 9-12 appear only on arrays.
159 return 65536 if tile_mode(mode) == 0 else 4096
160
161
162def element_bytes(fmt):
163 if fmt not in ELEMENT_BYTES:
164 raise LayoutError(f"no element-size mapping for DXGI format {fmt}")
165 return ELEMENT_BYTES[fmt]
166
167
168def surface_layout(width, height, fmt, mips, tile=4096):
169 """AMD Gfx10 surface layout: standalone mips smallest-first, then one tail tile.
170
171 Returns a dict with the allocation size, the first tail mip index, block
172 dimensions and a per-mip list. `offset` is relative to the allocation base.
173 """
174 eb = element_bytes(fmt)
175 log = {1: 0, 2: 1, 4: 2, 8: 3, 16: 4}[eb]
176 px = 4 if fmt in BC_FORMATS else 1
177 levels = 1
178 v = max(width, height)
179 while v > 1:
180 levels += 1
181 v >>= 1
182 if mips < 1 or mips > levels:
183 raise LayoutError(f"invalid mip count {mips} for {width}x{height}")
184 half_bits = 6 if tile == 4096 else 8
185 max_tail = 8 if tile == 4096 else 12
186 bw = 1 << (half_bits - log // 2)
187 bh = 1 << (half_bits - (log + 1) // 2)
188 mw, mh = {0: (16, 16), 1: (16, 8), 2: (8, 8), 3: (8, 4)}.get(log, (4, 4))
189 ew = (width + px - 1) // px
190 eh = (height + px - 1) // px
191 tail = mips
192 sizes = []
193 out = []
194 for i in range(mips):
195 wc = max(1, (ew + (1 << i) - 1) >> i)
196 hc = max(1, (eh + (1 << i) - 1) >> i)
197 if mips > 1 and wc <= bw // 2 and hc <= bh and mips - i <= max_tail:
198 tail = i
199 break
200 pw = align(wc, bw)
201 ph = align(hc, bh)
202 sizes.append(pw * ph * eb)
203 out.append(dict(index=i, blocks_w=wc, blocks_h=hc, padded_w=pw, padded_h=ph,
204 pixels_w=max(1, width >> i), pixels_h=max(1, height >> i),
205 offset=0, region=pw * ph * eb, tile_x=0, tile_y=0, in_tail=False))
206 off = tile if tail < mips else 0
207 for i in range(tail - 1, -1, -1):
208 out[i]["offset"] = off
209 off += sizes[i]
210 for i in range(tail, mips):
211 entry = max_tail - 1 - (i - tail)
212 moff = (16 << entry) if entry > 6 else entry << 8
213 x = y = 0
214 for bit in range(6):
215 x |= ((moff >> (9 + 2 * bit)) & 1) << bit
216 y |= ((moff >> (8 + 2 * bit)) & 1) << bit
217 wc = max(1, (ew + (1 << i) - 1) >> i)
218 hc = max(1, (eh + (1 << i) - 1) >> i)
219 out.append(dict(index=i, blocks_w=wc, blocks_h=hc, padded_w=bw, padded_h=bh,
220 pixels_w=max(1, width >> i), pixels_h=max(1, height >> i),
221 offset=0, region=tile, tile_x=x * mw, tile_y=y * mh,
222 in_tail=True, tail_offset=moff))
223 return dict(size=off, tile=tile, first_tail=tail, block_w=bw, block_h=bh,
224 element_bytes=eb, mips=out)
225
226
227def detile(layout, mip, tiled):
228 """Copy the mip's elements out of the tiled allocation into block-linear order."""
229 pat = (PATTERNS_4K if layout["tile"] == 4096 else PATTERNS_64K)[
230 {1: 0, 2: 1, 4: 2, 8: 3, 16: 4}[layout["element_bytes"]]]
231 bw, bh = layout["block_w"], layout["block_h"]
232 eb = layout["element_bytes"]
233 out = bytearray(mip["blocks_w"] * mip["blocks_h"] * eb)
234 for y in range(mip["blocks_h"]):
235 for x in range(mip["blocks_w"]):
236 off = ((y // bh) * (mip["padded_w"] // bw) + x // bw) * layout["tile"]
237 for bit, s in enumerate(pat):
238 if s > 0:
239 off |= (((x + mip["tile_x"]) >> (s - 1)) & 1) << bit
240 elif s < 0:
241 off |= (((y + mip["tile_y"]) >> (-s - 1)) & 1) << bit
242 at = (y * mip["blocks_w"] + x) * eb
243 out[at:at + eb] = tiled[off:off + eb]
244 return bytes(out)
245
246
247# --- BC decoding (color only; enough for the downsample check) -------------
248
249def _rgb565(c):
250 return ((c >> 11) & 31) * 255.0 / 31, ((c >> 5) & 63) * 255.0 / 63, (c & 31) * 255.0 / 31
251
252
253def decode_bc1_block(data, at):
254 c0, c1, idx = struct.unpack_from("<HHI", data, at)
255 p0, p1 = _rgb565(c0), _rgb565(c1)
256 if c0 > c1:
257 pal = [p0, p1, tuple((2 * a + b) / 3 for a, b in zip(p0, p1)),
258 tuple((a + 2 * b) / 3 for a, b in zip(p0, p1))]
259 else:
260 pal = [p0, p1, tuple((a + b) / 2 for a, b in zip(p0, p1)), (0.0, 0.0, 0.0)]
261 return [pal[(idx >> (2 * (y * 4 + x))) & 3] for y in range(4) for x in range(4)]
262
263
264def decode_bc4_block(data, at):
265 e0, e1 = data[at], data[at + 1]
266 bits = int.from_bytes(data[at + 2:at + 8], "little")
267 if e0 > e1:
268 pal = [e0, e1] + [((7 - i) * e0 + i * e1) // 7 for i in range(1, 7)]
269 else:
270 pal = [e0, e1] + [((5 - i) * e0 + i * e1) // 5 for i in range(1, 5)] + [0, 255]
271 vals = [pal[(bits >> (3 * (y * 4 + x))) & 7] for y in range(4) for x in range(4)]
272 return [(float(v),) * 3 for v in vals]
273
274
275def decode_pixels(fmt, data, blocks_w, blocks_h):
276 """Return one (r, g, b) per pixel, or None for a format this tool cannot decode."""
277 px = []
278 for by in range(blocks_h):
279 rows = [[None] * (blocks_w * 4) for _ in range(4)]
280 for bx in range(blocks_w):
281 at = (by * blocks_w + bx) * 16
282 if fmt in (71, 72):
283 blk = decode_bc1_block(data, (by * blocks_w + bx) * 8)
284 elif fmt in (77, 78):
285 blk = decode_bc1_block(data, at + 8)
286 elif fmt in (80,):
287 blk = decode_bc4_block(data, (by * blocks_w + bx) * 8, False)
288 elif fmt in (83,):
289 a = decode_bc4_block(data, at, False)
290 b = decode_bc4_block(data, at + 8, False)
291 blk = [(p[0], q[0], 0.0) for p, q in zip(a, b)]
292 else:
293 return None
294 for y in range(4):
295 for x in range(4):
296 rows[y][bx * 4 + x] = blk[y * 4 + x]
297 px.extend(rows)
298 return [p for row in px for p in row]
299
300
301def block_means(pixels, blocks_w, blocks_h):
302 out = []
303 for by in range(blocks_h):
304 for bx in range(blocks_w):
305 acc = [0.0, 0.0, 0.0]
306 for y in range(4):
307 for x in range(4):
308 q = pixels[(by * 4 + y) * (blocks_w * 4) + bx * 4 + x]
309 for k in range(3):
310 acc[k] += q[k]
311 out.append((acc[0] / 16, acc[1] / 16, acc[2] / 16))
312 return out
313
314
315def downsample2(blocks, blocks_w, blocks_h):
316 ow, oh = max(1, blocks_w // 2), max(1, blocks_h // 2)
317 out = []
318 for y in range(oh):
319 for x in range(ow):
320 acc = [0.0, 0.0, 0.0]
321 n = 0
322 for dy in range(2):
323 for dx in range(2):
324 bx = min(blocks_w - 1, 2 * x + dx)
325 by = min(blocks_h - 1, 2 * y + dy)
326 q = blocks[by * blocks_w + bx]
327 for k in range(3):
328 acc[k] += q[k]
329 n += 1
330 out.append(tuple(a / n for a in acc))
331 return out
332
333
334def mean_abs_error(a, b):
335 if not a:
336 return None
337 return sum(abs(x - y) for pa, pb in zip(a, b) for x, y in zip(pa, pb)) / (3 * len(a))
338
339
340# --- RDS5 / ETPF container ------------------------------------------------
341
342class Pool:
343 """Read-only RDS5 texture pool, mirroring TtpfReader's catalog checks."""
344
345 def __init__(self, path):
346 self.path = path
347 self._fh = open(path, "rb")
348 try:
349 self.data = mmap.mmap(self._fh.fileno(), 0, access=mmap.ACCESS_READ)
350 except Exception:
351 self._fh.close()
352 raise
353 d = self.data
354 if len(d) < 256 or d[:4] != b"RDS5":
355 raise ValueError("not an RDS5 container or truncated header")
356 count = u32(d, 4)
357 size_word = u64(d, 8)
358 self.virtual_size = size_word & 0x00FFFFFFFFFFFFFF
359 if (count < 3 or count > 1_000_002 or (size_word >> 56) != 22 or
360 self.virtual_size < 4096 or u32(d, 16) not in
361 ((count + 31) // 32, (count + 31) // 32 + 1)):
362 raise ValueError("unsupported RDS5 index layout")
363 self.chunk_count = count - 2
364 table_end = 24 + (count - 1) * 8
365 self.etpf = align(table_end, 256)
366 if table_end > len(d) - 16:
367 raise ValueError("RDS5 index exceeds its source")
368 table = d[24:table_end]
369 if ((u64(table, len(table) - 8) & 0x3FFFFFF) * 256 != len(d) or
370 ((u64(table, len(table) - 8) >> 30) & 0x3FFFFF) * 4096 != self.virtual_size):
371 raise ValueError("RDS5 sentinel does not match its lengths")
372 self.chunks = []
373 for i in range(self.chunk_count):
374 v, nxt = u64(table, i * 8), u64(table, (i + 1) * 8)
375 start, end = (v & 0x3FFFFFF) * 256, (nxt & 0x3FFFFFF) * 256
376 virt, vend = ((v >> 30) & 0x3FFFFF) * 4096, ((nxt >> 30) & 0x3FFFFF) * 4096
377 pad = v >> 52
378 codec = (v >> 26) & 15
379 packed, size = end - start - pad, vend - virt
380 if (start < self.etpf + 16 or end > len(d) or packed < 1 or packed > MAX_OUTPUT or
381 size < 1 or size > MAX_OUTPUT or vend > self.virtual_size or
382 (codec == 0 and packed != size)):
383 raise ValueError(f"RDS5 chunk {i} range is invalid")
384 self.chunks.append((virt, size, start, packed, codec, pad))
385 eh = d[self.etpf:self.etpf + 16]
386 if eh[:4] != b"ETPF" or u32(eh, 4) != ETPF_VERSION:
387 raise ValueError("unsupported embedded ETPF version")
388 self.textures = u32(eh, 8)
389 area = u32(eh, 12)
390 metadata = 16 + area + self.textures * 32
391 padded = align(metadata, 4096)
392 alignment = u32(d, 20)
393 source_padding = (alignment >> 28) * 256
394 if (self.textures < 1 or self.textures > MAX_TEXTURES or area < self.textures * 16 or
395 (alignment & 0x0FFFFFFF) != 0 or padded != self.chunks[0][0] or
396 self.etpf + padded + source_padding != self.chunks[0][2]):
397 raise ValueError("ETPF tables do not match the data boundary")
398 self.area = area
399 self.records = d[self.etpf + 16:self.etpf + 16 + area]
400 self.ids = d[self.etpf + 16 + area:self.etpf + 16 + area + self.textures * 32]
401 self._starts = [c[0] for c in self.chunks]
402
403 def close(self):
404 self.data.close()
405 self._fh.close()
406
407 def descriptor(self, index):
408 if not 0 <= index < self.textures:
409 raise IndexError(index)
410 a, b, c, d = struct.unpack_from("<IIII", self.records, index * 16)
411 return dict(
412 index=index, width=(a & 0x3FFF) + 1, height=((a >> 14) & 0x3FFF) + 1,
413 mips=(a >> 28) + (b & 7), packed_mips=a >> 28, non_tail=b & 7,
414 format=(b >> 3) & 255, depth=((b >> 11) & 1023) + 1,
415 dimension=(b >> 21) & 3, mode=b >> 23, meta=c >> 21, extra=d,
416 base=(c & 0x1FFFFF) * 4096, asset_key_at=(
417 u64(self.records, self.textures * 16 + index * 8)
418 if (self.textures * 16 + index * 8 + 8 <= len(self.records))
419 else None),
420 )
421
422 def chunks_for(self, start, size):
423 import bisect
424 end = start + size
425 i = max(0, bisect.bisect_right(self._starts, start) - 1)
426 out = []
427 covered = start
428 while i < len(self.chunks) and self.chunks[i][0] < end:
429 virt, csize, src, packed, codec, pad = self.chunks[i]
430 if virt > covered:
431 raise ValueError("texture crosses an unmapped virtual range")
432 out.append(self.chunks[i])
433 covered = min(end, virt + csize)
434 i += 1
435 if covered != end:
436 raise ValueError("texture range is not completely mapped")
437 return out
438
439 def codecs(self, start, size):
440 return {c[4] for c in self.chunks_for(start, size)}
441
442 def readable(self, start, size):
443 return self.codecs(start, size) <= {0, 8}
444
445 def read_range(self, start, size, cache=None):
446 cache = {} if cache is None else cache
447 out = bytearray(size)
448 for virt, csize, src, packed, codec, pad in self.chunks_for(start, size):
449 key = (src, packed, codec)
450 if key not in cache:
451 raw = self.data[src:src + packed]
452 if codec == 0:
453 cache[key] = bytes(raw)
454 elif codec == 8:
455 cache[key] = zlib.decompress(raw)
456 else:
457 raise BcpackRequired("range touches a BCPack chunk")
458 if len(cache[key]) != csize:
459 raise ValueError("decoded chunk length disagrees with its range")
460 lo, hi = max(start, virt), min(start + size, virt + csize)
461 out[lo - start:hi - start] = cache[key][lo - virt:hi - virt]
462 return bytes(out)
463
464 def span(self, index, base):
465 for j in range(index + 1, self.textures):
466 cand = (u32(self.records, j * 16 + 8) & 0x1FFFFF) * 4096
467 if cand < base:
468 return None
469 if cand > base:
470 return cand - base
471 return self.virtual_size - base
472
473
474def compact_row(desc):
475 """The reader's compact-profile gate (mode families 4/6/36 and aux mode 2)."""
476 return desc["mode"] in (4, 6, 36) or (desc["mode"] == 2 and (desc["meta"] or desc["extra"]))
477
478
479def validated_compact(desc, eb):
480 return (desc["mode"], desc["width"], desc["height"], desc["mips"], desc["non_tail"],
481 eb, desc["meta"], desc["extra"]) in VALIDATED_COMPACT
482
483
484def validated_aux(desc):
485 a = VALIDATED_AUX
486 return (desc["mips"] == a["mips"] and desc["non_tail"] == a["non_tail"] and
487 desc["meta"] == a["meta"] and desc["extra"] == a["extra"] and
488 desc["width"] == a["width"] and
489 ((desc["height"] == a["height_a"] and desc["format"] == a["fmt_a"]) or
490 (desc["height"] == a["height_b"] and desc["format"] in BC_FORMATS and
491 ELEMENT_BYTES.get(desc["format"]) == a["bytes_b"])))
492
493
494def analyze(pool, index):
495 """Descriptor + layout + per-mip codec availability for one texture."""
496 d = pool.descriptor(index)
497 out = dict(descriptor=d, tile_mode=tile_mode(d["mode"]), tile=tile_bytes(d["mode"]))
498 if d["dimension"] != 1 or d["depth"] != 1:
499 out["blocked"] = "array/volume descriptor"
500 return out
501 try:
502 layout = surface_layout(d["width"], d["height"], d["format"], d["mips"],
503 out["tile"])
504 except LayoutError as e:
505 out["blocked"] = str(e)
506 return out
507 out["layout"] = layout
508 if d["base"] == 0 or (d["base"] >> 12) == 0x1FFFFF:
509 out["blocked"] = "no mapped allocation"
510 return out
511 span = pool.span(index, d["base"])
512 out["allocation_span"] = span
513 out["span_matches"] = span == layout["size"]
514 if not out["span_matches"]:
515 out["blocked"] = "layout does not match the allocation span"
516 return out
517 avail = []
518 for mip in layout["mips"]:
519 try:
520 avail.append(pool.readable(d["base"] + mip["offset"], mip["region"]))
521 except ValueError:
522 avail = []
523 break
524 out["available"] = avail
525 if avail:
526 limit = d["non_tail"] if compact_row(d) else d["mips"]
527 limit = max(0, min(limit, len(avail)))
528 base_mip = next((i for i in range(limit) if avail[i]), None)
529 exported = 0
530 if base_mip is not None:
531 while base_mip + exported < limit and avail[base_mip + exported]:
532 exported += 1
533 out["reader_limit"] = limit
534 out["reader_base_mip"] = base_mip
535 out["reader_exported"] = exported
536 out["full_chain"] = bool(avail) and all(avail)
537 out["recoverable_mips"] = sum(1 for a in avail[exported:] if a) if base_mip == 0 else 0
538 return out
539
540
541# --- commands --------------------------------------------------------------
542
543def find_pools(arg):
544 if os.path.isfile(arg):
545 return [arg]
546 pools = sorted(glob.glob(os.path.join(arg, "data", "ttdb", "**", "*.ttpf"), recursive=True))
547 pools += sorted(glob.glob(os.path.join(arg, "pack", "*", "data", "ttdb", "**", "*.ttpf"),
548 recursive=True))
549 return pools
550
551
552def scan_pools(paths, as_json=None):
553 total = dict(pools=0, entries=0, arrays=0, unsupported_format=0, format11=0,
554 layout_mismatch=0, reader_full=0, reader_partial=0,
555 reader_skip_bcpack=0, whitelist_gated=0, gated_layout_ok=0,
556 gated_full_chain=0, gated_full_mips=0, gated_full_bytes=0,
557 gated_tail_only=0, gated_by_mode={},
558 compact_partial_rows=0, compact_missing_mips=0,
559 compact_decodable_mips=0, compact_decodable_bytes=0,
560 compact_missing_standalone=0, compact_missing_tail=0,
561 compact_rows_measured=0, compact_non_tail_before_tail=0,
562 compact_standalone_beyond_limit=0,
563 compact_standalone_decodable_beyond_limit=0,
564 compact_full_rows=0, tile_modes={})
565 for path in paths:
566 pool = Pool(path)
567 try:
568 total["pools"] += 1
569 for i in range(pool.textures):
570 d = pool.descriptor(i)
571 total["entries"] += 1
572 tm = str(tile_mode(d["mode"]))
573 total["tile_modes"][tm] = total["tile_modes"].get(tm, 0) + 1
574 if d["dimension"] != 1 or d["depth"] != 1:
575 total["arrays"] += 1
576 continue
577 # The reader's gate: modes 4/6/36 and aux mode 2 need a validated tuple;
578 # every other non-0/2 mode is rejected by the same branch.
579 aux = d["mode"] == 2 and (d["meta"] or d["extra"])
580 if d["mode"] in (0, 2):
581 gated = d["mode"] == 2 and aux and not validated_aux(d)
582 else:
583 eb = ELEMENT_BYTES.get(d["format"])
584 gated = not (d["mode"] in (4, 6, 36) and eb is not None and
585 validated_compact(d, eb))
586 try:
587 layout = surface_layout(d["width"], d["height"], d["format"],
588 d["mips"], tile_bytes(d["mode"]))
589 except LayoutError:
590 total["unsupported_format"] += 1
591 if d["format"] == 11:
592 total["format11"] += 1
593 if gated:
594 total["whitelist_gated"] += 1
595 continue
596 span = pool.span(i, d["base"])
597 if d["base"] == 0 or span != layout["size"]:
598 total["layout_mismatch"] += 1
599 continue
600 avail = []
601 for mip in layout["mips"]:
602 try:
603 avail.append(pool.readable(d["base"] + mip["offset"], mip["region"]))
604 except ValueError:
605 avail = []
606 break
607 if not avail:
608 total["layout_mismatch"] += 1
609 continue
610 if gated:
611 total["whitelist_gated"] += 1
612 total["gated_layout_ok"] += 1
613 key = str(d["mode"])
614 total["gated_by_mode"][key] = total["gated_by_mode"].get(key, 0) + 1
615 if all(avail):
616 total["gated_full_chain"] += 1
617 total["gated_full_mips"] += d["mips"]
618 total["gated_full_bytes"] += sum(
619 mip["blocks_w"] * mip["blocks_h"] * layout["element_bytes"]
620 for mip in layout["mips"])
621 elif (layout["first_tail"] < d["mips"] and
622 all(avail[k] for k in range(layout["first_tail"], d["mips"]))):
623 total["gated_tail_only"] += 1
624 continue
625 is_compact = compact_row(d)
626 limit = min(d["non_tail"], len(avail)) if is_compact else len(avail)
627 base_mip = next((k for k in range(limit) if avail[k]), None)
628 exported = 0
629 if base_mip is not None:
630 while base_mip + exported < limit and avail[base_mip + exported]:
631 exported += 1
632 if exported == 0:
633 total["reader_skip_bcpack"] += 1
634 elif exported < d["mips"]:
635 total["reader_partial"] += 1
636 if is_compact and base_mip == 0 and exported == limit:
637 total["compact_partial_rows"] += 1
638 missing = d["mips"] - exported
639 total["compact_missing_mips"] += missing
640 dec = 0
641 for k in range(exported, d["mips"]):
642 if avail[k]:
643 dec += 1
644 if k < layout["first_tail"]:
645 total["compact_missing_standalone"] += 1
646 else:
647 total["compact_missing_tail"] += 1
648 total["compact_decodable_mips"] += dec
649 total["compact_decodable_bytes"] += sum(
650 layout["mips"][k]["blocks_w"] * layout["mips"][k]["blocks_h"] *
651 layout["element_bytes"] for k in range(exported, d["mips"])
652 if avail[k])
653 if dec == missing:
654 total["compact_full_rows"] += 1
655 else:
656 total["reader_full"] += 1
657 if d["mode"] in (4, 6, 36):
658 total["compact_rows_measured"] += 1
659 if d["non_tail"] < layout["first_tail"]:
660 total["compact_non_tail_before_tail"] += 1
661 total["compact_standalone_beyond_limit"] += (
662 layout["first_tail"] - d["non_tail"])
663 total["compact_standalone_decodable_beyond_limit"] += sum(
664 1 for k in range(d["non_tail"], layout["first_tail"]) if avail[k])
665 finally:
666 pool.close()
667 report = dict(total=total)
668 if as_json:
669 with open(as_json, "w", encoding="utf-8") as f:
670 json.dump(report, f, indent=1)
671 print(json.dumps(report, indent=1))
672
673
674def describe(pool, index):
675 a = analyze(pool, index)
676 d = a["descriptor"]
677 out = dict(index=index, width=d["width"], height=d["height"], format=d["format"],
678 mips=d["mips"], non_tail=d["non_tail"], mode=d["mode"],
679 tile_mode=a["tile_mode"], tile=a["tile"], base=d["base"],
680 meta=d["meta"], extra=d["extra"])
681 if "layout" in a:
682 out["allocation_size"] = a["layout"]["size"]
683 out["allocation_span"] = a.get("allocation_span")
684 out["span_matches"] = a.get("span_matches")
685 out["first_tail_mip"] = a["layout"]["first_tail"]
686 out["mips_detail"] = [
687 dict(index=m["index"], blocks=[m["blocks_w"], m["blocks_h"]], offset=m["offset"],
688 region=m["region"], tail=m["in_tail"], tile_origin=[m["tile_x"], m["tile_y"]])
689 for m in a["layout"]["mips"]]
690 if "available" in a:
691 out["available"] = a["available"]
692 out["reader_limit"] = a["reader_limit"]
693 out["reader_exported"] = a["reader_exported"]
694 out["full_chain"] = a["full_chain"]
695 if a.get("blocked"):
696 out["blocked"] = a["blocked"]
697 return out
698
699
700def check(pool, index):
701 a = analyze(pool, index)
702 if "layout" not in a:
703 print(json.dumps(dict(index=index, blocked=a.get("blocked")), indent=1))
704 return 2
705 layout = a["layout"]
706 d = a["descriptor"]
707 cache = {}
708 try:
709 tiled = pool.read_range(d["base"], layout["size"], cache)
710 except BcpackRequired:
711 print(json.dumps(dict(index=index, blocked="BCPack in allocation"), indent=1))
712 return 2
713 decoded, means = [], []
714 for mip in layout["mips"]:
715 data = detile(layout, mip, tiled[mip["offset"]:mip["offset"] + mip["region"]])
716 px = decode_pixels(d["format"], data, mip["blocks_w"], mip["blocks_h"])
717 if px is None:
718 decoded.append(None)
719 means.append(None)
720 else:
721 decoded.append(px)
722 means.append(block_means(px, mip["blocks_w"], mip["blocks_h"]))
723 if all(px is None for px in decoded):
724 print(json.dumps(dict(index=index, blocked=(
725 f"format {d['format']} is not one of the BC formats this tool decodes "
726 "(71/72/77/78/80/83)")), indent=1))
727 return 2
728 errs = []
729 for k in range(1, d["mips"]):
730 if means[k - 1] is None or means[k] is None:
731 errs.append(None)
732 continue
733 pm = layout["mips"][k - 1]
734 cm = layout["mips"][k]
735 errs.append(round(mean_abs_error(downsample2(means[k - 1], pm["blocks_w"], pm["blocks_h"]),
736 means[k]), 2))
737 control = None
738 if layout["first_tail"] < d["mips"] and decoded[layout["first_tail"] - 1] is not None:
739 tm = layout["mips"][layout["first_tail"]]
740 bad = dict(tm, tile_x=0, tile_y=0)
741 data = detile(layout, bad, tiled[:layout["tile"]])
742 px = decode_pixels(d["format"], data, tm["blocks_w"], tm["blocks_h"])
743 if px is not None:
744 pm = layout["mips"][layout["first_tail"] - 1]
745 control = round(mean_abs_error(
746 downsample2(means[layout["first_tail"] - 1], pm["blocks_w"], pm["blocks_h"]),
747 block_means(px, tm["blocks_w"], tm["blocks_h"])), 2)
748 result = dict(index=index, width=d["width"], height=d["height"], format=d["format"],
749 mips=d["mips"], non_tail=d["non_tail"], first_tail=layout["first_tail"],
750 tile=layout["tile"], chain_error=errs, max_error=max(
751 (e for e in errs if e is not None), default=None),
752 tail_origin_control=control, full_chain=a.get("full_chain"))
753 print(json.dumps(result, indent=1))
754 return 0 if all(e is not None and e <= 6 for e in errs) else 1
755
756
757def dds_bytes(width, height, fmt, mips, linear, payload):
758 hdr = bytearray(128)
759 hdr[0:4] = b"DDS "
760 flags = 0x81007 if mips == 1 else 0xA1007
761 struct.pack_into("<IIIIIII", hdr, 4, 124, flags, height, width, linear, 0, mips)
762 struct.pack_into("<II4s", hdr, 76, 32, 4, b"DX10")
763 struct.pack_into("<II", hdr, 108, 0x1000 if mips == 1 else 0x401008, 0)
764 return bytes(hdr) + struct.pack("<IIIII", fmt, 3, 0, 1, 0) + payload
765
766
767def export(pool, index, out_path, mips=None, force=False):
768 a = analyze(pool, index)
769 if "layout" not in a or "available" not in a:
770 print(f"texture {index}: {a.get('blocked', 'layout unavailable')}", file=sys.stderr)
771 return 2
772 d = a["descriptor"]
773 if d["format"] not in BC_FORMATS:
774 print(f"texture {index}: format {d['format']} is uncompressed; this tool does not "
775 "validate uncompressed tiling, so it will not write a DDS", file=sys.stderr)
776 return 2
777 if not a["full_chain"]:
778 print(f"texture {index}: not every source mip is zlib/raw; refusing to mix BCPack",
779 file=sys.stderr)
780 return 2
781 count = d["mips"] if mips is None else mips
782 if count < 1 or count > d["mips"]:
783 print(f"texture {index}: --mips must be 1..{d['mips']}", file=sys.stderr)
784 return 2
785 layout = a["layout"]
786 cache = {}
787 payload = bytearray()
788 for mip in layout["mips"][:count]:
789 tiled = pool.read_range(d["base"] + mip["offset"], mip["region"], cache)
790 payload += detile(layout, mip, tiled)
791 if 148 + len(payload) > MAX_OUTPUT:
792 print("DDS exceeds the 256 MiB output limit", file=sys.stderr)
793 return 2
794 if os.path.exists(out_path) and not force:
795 print(f"{out_path} exists; pass --force to replace it", file=sys.stderr)
796 return 2
797 top = layout["mips"][0]
798 linear = (top["blocks_w"] * top["blocks_h"] * layout["element_bytes"]
799 if d["format"] in BC_FORMATS else d["width"] * layout["element_bytes"])
800 with open(out_path, "wb") as f:
801 f.write(dds_bytes(d["width"], d["height"], d["format"], count, linear, payload))
802 print(f"texture {index}: {d['width']}x{d['height']} fmt {d['format']} {count} mips "
803 f"({148 + len(payload)} bytes) -> {out_path}")
804 return 0
805
806
807def main(argv=None):
808 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
809 sub = ap.add_subparsers(dest="cmd", required=True)
810 ps = sub.add_parser("scan", help="aggregate counters over pools")
811 ps.add_argument("paths", nargs="+")
812 ps.add_argument("--json")
813 pl = sub.add_parser("layout", help="descriptor fields and mip offsets")
814 pl.add_argument("pool")
815 pl.add_argument("index", type=int)
816 pc = sub.add_parser("check", help="decode a chain and report downsample error")
817 pc.add_argument("pool")
818 pc.add_argument("index", type=int)
819 pe = sub.add_parser("export", help="write the full zlib/raw chain as DDS")
820 pe.add_argument("pool")
821 pe.add_argument("index", type=int)
822 pe.add_argument("out")
823 pe.add_argument("--mips", type=int)
824 pe.add_argument("--force", action="store_true")
825 a = ap.parse_args(argv)
826 if a.cmd == "scan":
827 pools = []
828 for p in a.paths:
829 pools += find_pools(p)
830 scan_pools(pools, a.json)
831 return 0
832 pool = Pool(a.pool)
833 try:
834 if a.cmd == "layout":
835 print(json.dumps(describe(pool, a.index), indent=1))
836 return 0
837 if a.cmd == "check":
838 return check(pool, a.index)
839 return export(pool, a.index, a.out, a.mips, a.force)
840 finally:
841 pool.close()
842
843
844if __name__ == "__main__":
845 sys.exit(main())
diff --git a/tools/world_census.py b/tools/world_census.py
new file mode 100644
index 000000000..2a59decbb
--- /dev/null
+++ b/tools/world_census.py
@@ -0,0 +1,697 @@
1"""Census every 0x7a map resource in an RPF9 archive, with measured byte coverage.
2
3The archive table of contents is encrypted, but file payloads are zlib streams (and some graphics pages are
4stored raw). This walks the data area in independent byte shards, inflates every stream, validates the 0x7a
5header/schema, and joins the contiguous continuation streams of a split resource. Each shard writes its map
6rows, accepted stream intervals and 0x6 page extents; the merge step counts maps/entities, finds duplicate
7payloads, measures unread bytes, and audits the gaps for a 0x7a signature the walker did not read.
8
9Usage:
10 python -I world_census.py <archive.rpf> [--out DIR] [--shard-size BYTES] [--jobs N]
11 [--start N] [--limit BYTES] [--resume] [--merge-only]
12
13Only aggregate metadata is written: resource offsets/sizes, map/entity counts, extents and content hashes.
14No carved stream, model or texture is kept.
15"""
16from __future__ import annotations
17
18import argparse
19import bisect
20import hashlib
21import json
22import mmap
23import os
24import re
25import struct
26import sys
27import time
28import zlib
29from concurrent.futures import ProcessPoolExecutor, as_completed
30
31_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
32if _TOOLS_DIR not in sys.path:
33 sys.path.insert(0, _TOOLS_DIR)
34
35import world_index as WI
36
37ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]")
38SIG = b"0DRP"
39VERSION = 0x7A
40CAP = 64 << 20
41CHUNK = 1 << 20
42WARMUP = 8 << 20
43JOIN_MAX = 64
44BAND_GAP = 64 << 20
45GAP_CHUNK = 4 << 20
46FORMAT = 3
47
48
49def inflate(m, s, size, max_inflate=CAP, keep=False):
50 """Inflate one zlib stream.
51
52 Returns (data, used, eof, is_meta, inflated, truncated). ``used`` is the stored compressed length;
53 ``inflated`` counts the whole output even when only a 0x7a stream is kept.
54 """
55 d = zlib.decompressobj()
56 chunks = []
57 kept = 0
58 inflated = 0
59 carry = bytearray()
60 decided = False
61 is_meta = False
62 truncated = False
63 p = s
64 while not d.eof and p < size:
65 piece = m[p:p + CHUNK]
66 if not piece:
67 break
68 produced = d.decompress(piece)
69 p += len(piece)
70 inflated += len(produced)
71 if not decided:
72 carry.extend(produced)
73 if len(carry) >= 0x15:
74 decided = True
75 is_meta = bytes(carry[0x10:0x15]) == b"0DRPz"
76 if is_meta or keep:
77 take = bytes(carry[:max(0, max_inflate - kept)])
78 chunks.append(take)
79 kept += len(take)
80 truncated = len(take) < len(carry)
81 carry = None
82 elif is_meta or keep:
83 if kept < max_inflate:
84 take = produced[:max_inflate - kept]
85 chunks.append(take)
86 kept += len(take)
87 truncated = truncated or len(take) < len(produced)
88 elif produced:
89 truncated = True
90 if d.unused_data or d.eof:
91 break
92 if not d.eof:
93 return b"", 0, False, False, inflated, False
94 used = p - s - len(d.unused_data)
95 return b"".join(chunks), used, True, is_meta, inflated, truncated
96
97
98def required_len(b):
99 """Highest system offset (0x5 segment) referenced by a 0x7a resource's tables and blocks."""
100 if len(b) < 0x50 or b[0x10:0x14] != SIG or b[0x14] != VERSION:
101 return 0
102 nst, nen, nbl = struct.unpack_from("<HHH", b, 0x48)
103 if not (1 <= nst <= 4096 and nbl <= 4096 and nen <= 4096) or nbl == 0:
104 return 0
105 need = len(b)
106 for ptr, count, width in ((struct.unpack_from("<Q", b, 0x28)[0], nst, 32),
107 (struct.unpack_from("<Q", b, 0x38)[0], nbl, 16)):
108 if ptr >> 28 != 5:
109 return 0
110 need = max(need, (ptr & 0x0FFFFFFF) + count * width)
111 st = struct.unpack_from("<Q", b, 0x28)[0] & 0x0FFFFFFF
112 if st + 32 * nst > len(b):
113 return need
114 for i in range(nst):
115 o = st + 32 * i
116 count = struct.unpack_from("<H", b, o + 0x1E)[0]
117 table = struct.unpack_from("<Q", b, o + 0x10)[0]
118 if not count:
119 continue
120 if table >> 28 != 5:
121 return 0
122 need = max(need, (table & 0x0FFFFFFF) + 16 * count)
123 it = struct.unpack_from("<Q", b, 0x38)[0] & 0x0FFFFFFF
124 if it + 16 * nbl > len(b):
125 return need
126 for i in range(nbl):
127 o = it + 16 * i
128 size, ptr = struct.unpack_from("<I", b, o + 4)[0], struct.unpack_from("<Q", b, o + 8)[0]
129 if size > (1 << 24):
130 return 0
131 if ptr >> 28 == 5:
132 need = max(need, (ptr & 0x0FFFFFFF) + size)
133 return need
134
135
136def needs_more(b):
137 """True when a 0x7a header points at system data beyond this stream (a split resource)."""
138 return required_len(b) > len(b)
139
140
141def assemble(m, s, size):
142 """Inflate a 0x7a stream and its continuation pages.
143
144 A continuation is normally the next contiguous zlib stream, but a page that does not compress is stored raw.
145 Returns None for a stream that does not end inside the archive. Otherwise a dict with the joined bytes,
146 stored length of the zlib parts, raw continuation length, spans and whether all system pointers resolve.
147 """
148 data, used, eof, is_meta, inflated, truncated = inflate(m, s, size)
149 if not eof:
150 return None
151 out = {"data": data, "used": used, "raw_system": 0, "streams": 1, "pages": 1,
152 "inflated": inflated, "is_meta": is_meta, "truncated": truncated,
153 "spans": [(s, used)], "raw_spans": [], "joined": False, "end": s + used}
154 if not is_meta:
155 return out
156 while out["pages"] < JOIN_MAX:
157 row = WI.parse_resource(out["data"])
158 if row is not None and not needs_more(out["data"]):
159 break
160 if out["truncated"] or out["pages"] >= JOIN_MAX:
161 break
162 nxt = (out["end"] + 15) & ~15
163 if nxt >= size:
164 break
165 if ZHDR.match(m, nxt, size):
166 more, mused, meof, mmeta, minfl, mtrunc = inflate(m, nxt, size, keep=True)
167 if not meof:
168 break
169 if mmeta:
170 # A continuation never starts a second 0x7a resource; this one is truncated.
171 break
172 out["data"] += more
173 out["used"] += mused
174 out["inflated"] += minfl
175 out["streams"] += 1
176 out["pages"] += 1
177 out["joined"] = True
178 out["truncated"] = out["truncated"] or mtrunc
179 out["spans"].append((nxt, mused))
180 out["end"] = nxt + mused
181 continue
182 need = required_len(out["data"])
183 take = need - len(out["data"])
184 if take <= 0 or take > (64 << 20) or nxt + take > size:
185 break
186 extra = m[nxt:nxt + take]
187 if not extra or extra.count(0) == len(extra):
188 break
189 out["data"] += extra
190 out["raw_system"] += take
191 out["pages"] += 1
192 out["joined"] = True
193 out["raw_spans"].append((nxt, take))
194 out["end"] = nxt + take
195 out["complete"] = (not out["truncated"] and WI.parse_resource(out["data"]) is not None
196 and not needs_more(out["data"]))
197 return out
198
199
200def gfx_extent(data):
201 """Return (graphics block count, highest 0x6 offset+size) for a parsed 0x7a resource."""
202 it = WI._ptr(WI._u64(data, 0x38), len(data))
203 count = need = 0
204 for i in range(WI._u16(data, 0x4C) if it is not None else 0):
205 o = it + 16 * i
206 size, ptr = WI._u32(data, o + 4), WI._u64(data, o + 8)
207 if ptr >> 28 == 6:
208 count += 1
209 need = max(need, (ptr & 0x0FFFFFFF) + size)
210 return count, need
211
212
213def has_map_root(data):
214 """True when the resource's schema includes CMapData, even if it has no CEntityDef."""
215 st = WI._ptr(WI._u64(data, 0x28), len(data))
216 return st is not None and any(WI._u32(data, st + 32 * i) == WI.MAPDATA
217 for i in range(WI._u16(data, 0x48)))
218
219
220def inspect_map(data, row, res):
221 """Add the exactness diagnostics and payload hash to a parsed map row."""
222 out = dict(row)
223 out.update({"offset": res["offset"], "size": len(data), "stored": res["used"],
224 "raw_system": res["raw_system"], "inflated": res["inflated"],
225 "streams": res["streams"], "sha1": hashlib.sha1(data).hexdigest(),
226 "system_end": res["end"]})
227 entity_size = out.get("entity_size") or 0
228 it = WI._ptr(WI._u64(data, 0x38), len(data))
229 blocks = WI._u16(data, 0x4C) if it is not None else 0
230 counted = graphics = unresolved = duplicate = gfx = 0
231 gfx_need = 0
232 seen = set()
233 for i in range(blocks):
234 o = it + 16 * i
235 name, size, ptr = WI._u32(data, o), WI._u32(data, o + 4), WI._u64(data, o + 8)
236 hi = ptr >> 28
237 off = ptr & 0x0FFFFFFF
238 key = (name, off, size)
239 if key in seen:
240 duplicate += 1
241 seen.add(key)
242 if name == WI.ENTITY:
243 if hi == 5 and entity_size and size % entity_size == 0 and off + size <= len(data):
244 counted += 1
245 elif hi == 6:
246 graphics += 1
247 else:
248 unresolved += 1
249 elif hi == 6:
250 gfx += 1
251 gfx_need = max(gfx_need, off + size)
252 out.update({"entity_blocks_counted": counted, "entity_blocks_graphics": graphics,
253 "entity_blocks_unresolved": unresolved, "duplicate_blocks": duplicate,
254 "gfx_blocks": gfx, "gfx_need": gfx_need,
255 "exact": graphics == 0 and unresolved == 0 and duplicate == 0})
256 return out
257
258
259def scan_shard(job):
260 """Scan one [start, end) window and write its rows, intervals and stats to outdir."""
261 archive, index, start, end, outdir, data_start = job
262 t0 = time.time()
263 stats = {"streams": 0, "stored": 0, "raw_system": 0, "inflated": 0, "rejected": 0, "meta": 0,
264 "map_meta": 0, "meta_other": 0, "map_meta_bytes": 0,
265 "invalid": 0, "incomplete": 0, "join_max": 0, "entity_gfx": 0,
266 "entity_unresolved": 0, "adopted": 0}
267 rows, intervals, raw_pages, raw_system = [], [], [], []
268 with open(archive, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m:
269 size = len(m)
270 pos = max(data_start, start - WARMUP)
271 search_end = min(size, end + 16)
272 while pos < search_end:
273 found = ZHDR.search(m, pos, search_end)
274 if not found:
275 break
276 s = found.start()
277 if s >= end:
278 break
279 if s % 16:
280 pos = s + 1
281 continue
282 try:
283 res = assemble(m, s, size)
284 except (zlib.error, struct.error, IndexError):
285 stats["rejected"] += 1
286 pos = s + 1
287 continue
288 if res is None:
289 stats["rejected"] += 1
290 pos = s + 1
291 continue
292 for a, used in res["spans"]:
293 intervals.append([a, a + used])
294 raw_system.extend([a, a + used] for a, used in res["raw_spans"])
295 stats["streams"] += res["streams"]
296 stats["stored"] += res["used"]
297 stats["raw_system"] += res["raw_system"]
298 stats["inflated"] += res["inflated"]
299 pos = res["end"]
300 if pos <= s:
301 pos = s + 1
302 if not res["is_meta"]:
303 continue
304 if not res["complete"]:
305 stats["incomplete"] += 1
306 continue
307 row = WI.parse_resource(res["data"])
308 if row is None:
309 stats["invalid"] += 1
310 continue
311 res["offset"] = s
312 if row["kind"] != "map":
313 stats["meta"] += 1
314 if has_map_root(res["data"]):
315 stats["map_meta"] += 1
316 stats["map_meta_bytes"] += len(res["data"])
317 else:
318 stats["meta_other"] += 1
319 stats["join_max"] = max(stats["join_max"], res["pages"])
320 _, need = gfx_extent(res["data"])
321 if need:
322 raw_pages.append([(res["end"] + 15) & ~15, need])
323 continue
324 maprow = inspect_map(res["data"], row, res)
325 stats["join_max"] = max(stats["join_max"], res["pages"])
326 stats["entity_gfx"] += maprow["entity_blocks_graphics"]
327 stats["entity_unresolved"] += maprow["entity_blocks_unresolved"]
328 if s < start:
329 stats["adopted"] += 1
330 continue
331 rows.append(maprow)
332 if maprow["gfx_need"]:
333 raw_pages.append([(res["end"] + 15) & ~15, maprow["gfx_need"]])
334 rows.sort(key=lambda r: r["offset"])
335 doc = {"index": index, "start": start, "end": end, "archive_size": size,
336 "data_start": data_start, "elapsed": round(time.time() - t0, 3),
337 "complete": True, "format": FORMAT, "stats": stats, "rows": rows,
338 "intervals": intervals, "raw_pages": raw_pages, "raw_system": raw_system,
339 "map_first": rows[0]["offset"] if rows else None,
340 "map_last": rows[-1]["offset"] if rows else None}
341 path = os.path.join(outdir, "shard_%03d_%d_%d.json" % (index, start, end))
342 tmp = path + ".tmp"
343 with open(tmp, "w", encoding="utf-8") as f:
344 json.dump(doc, f, separators=(",", ":"))
345 os.replace(tmp, path)
346 return {"index": index, "start": start, "end": end, "elapsed": doc["elapsed"],
347 "maps": len(rows), "entities": sum(r["entities"] for r in rows), **stats}
348
349
350def _peek_meta(m, s, end):
351 """True when a zlib stream at s inflates to a 0x7a header; used only to audit gaps."""
352 d = zlib.decompressobj()
353 out = bytearray()
354 p = s
355 while len(out) < 0x15 and p < end:
356 piece = m[p:p + 256]
357 if not piece:
358 break
359 try:
360 out.extend(d.decompress(piece))
361 except zlib.error:
362 return False
363 p += len(piece)
364 if d.eof:
365 break
366 return len(out) >= 0x15 and out[0x10:0x15] == b"0DRPz"
367
368
369def classify_gaps(archive, intervals, raw_pages, raw_system, scan_start, scan_end):
370 """Merge accepted stream spans and account for every byte in the scanned range.
371
372 ``raw_pages`` are 0x6 graphics extents and ``raw_system`` are uncompressed system-continuation spans;
373 both are payload of an adjacent resource, not unexplained bytes.
374 """
375 spans = sorted((max(scan_start, a), min(scan_end, b)) for a, b in intervals if b > scan_start and a < scan_end)
376 merged = []
377 for a, b in spans:
378 if a >= b:
379 continue
380 if merged and a <= merged[-1][1]:
381 merged[-1][1] = max(merged[-1][1], b)
382 else:
383 merged.append([a, b])
384 segments = [(a, a + need, "raw_graphics") for a, need in raw_pages]
385 segments += [(a, b, "raw_system") for a, b in raw_system if b > a]
386 segments.sort()
387 starts = [s[0] for s in segments]
388 covered = sum(b - a for a, b in merged)
389 result = {"covered": covered, "raw_graphics": 0, "raw_system": 0, "zero_padding": 0, "unread": 0,
390 "gaps": 0, "unread_sample": [], "raw_0drp": 0,
391 "raw_0drp_offsets": [], "gap_0drp": 0, "gap_0drp_other": 0,
392 "raw_maps": 0, "raw_meta": 0, "missed_zlib_meta": 0,
393 "missed_zlib_offsets": []}
394 with open(archive, "rb") as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m:
395 cursor = scan_start
396 bounds = merged + [[scan_end, scan_end]]
397 for a, b in bounds:
398 if cursor < a:
399 result["gaps"] += 1
400 pos = cursor
401 idx = bisect.bisect_left(starts, cursor)
402 while idx < len(segments) and segments[idx][0] < a:
403 s0, s1, kind = segments[idx]
404 start = max(pos, s0)
405 if start > pos:
406 _count_gap(m, pos, start, result)
407 take = max(0, min(s1, a) - start)
408 if take:
409 result[kind] += take
410 _audit_gap(m, start, start + take, result, allow_zlib=True)
411 pos = max(pos, start + take)
412 idx += 1
413 if pos < a:
414 _count_gap(m, pos, a, result)
415 _audit_gap(m, pos, a, result, allow_zlib=True)
416 cursor = max(cursor, b)
417 result["accounted"] = (result["covered"] + result["raw_graphics"] + result["raw_system"]
418 + result["zero_padding"] + result["unread"])
419 result["span"] = scan_end - scan_start
420 result["coverage"] = result["covered"] / result["span"] if result["span"] else 0.0
421 result["accounted_ratio"] = result["accounted"] / result["span"] if result["span"] else 0.0
422 if len(result["unread_sample"]) > 200:
423 result["unread_sample"] = result["unread_sample"][:200]
424 return result
425
426
427def _count_gap(m, a, b, result):
428 if a >= b:
429 return
430 p = a
431 while p < b:
432 piece = m[p:min(b, p + GAP_CHUNK)]
433 if not piece:
434 break
435 zero = piece.count(0)
436 result["zero_padding"] += zero
437 nz = len(piece) - zero
438 if nz:
439 result["unread"] += nz
440 if len(result["unread_sample"]) < 200:
441 i = next(k for k, c in enumerate(piece) if c)
442 result["unread_sample"].append([p + i, nz])
443 p += len(piece)
444
445
446def _audit_gap(m, a, b, result, allow_zlib):
447 """Search an unread gap for a 0x7a signature or an unaligned zlib stream that hides one."""
448 if a >= b:
449 return
450 p = a
451 while p < b:
452 piece = m[p:min(b, p + GAP_CHUNK)]
453 if not piece:
454 break
455 q = 0
456 while True:
457 i = piece.find(SIG, q)
458 if i < 0:
459 break
460 at = p + i
461 if at + 5 <= b and piece[i + 4] == VERSION:
462 result["gap_0drp"] += 1
463 start = at - 0x10
464 if start >= 0:
465 head = m[start:start + 0x18]
466 if len(head) == 0x18 and head[:8] == b"\0" * 8 and (struct.unpack_from("<Q", head, 8)[0] >> 28) == 5:
467 row = WI.parse_resource(m[start:start + CAP])
468 if row is not None:
469 if row.get("kind") == "map":
470 result["raw_maps"] += 1
471 else:
472 result["raw_meta"] += 1
473 result["raw_0drp"] += 1
474 if len(result["raw_0drp_offsets"]) < 50:
475 result["raw_0drp_offsets"].append(at)
476 else:
477 result["gap_0drp_other"] += 1
478 else:
479 result["gap_0drp_other"] += 1
480 q = i + 1
481 if allow_zlib:
482 q = 0
483 while True:
484 mt = ZHDR.search(piece, q)
485 if not mt:
486 break
487 at = p + mt.start()
488 if at % 16:
489 if at + 5 <= b and _peek_meta(m, at, b):
490 result["missed_zlib_meta"] += 1
491 if len(result["missed_zlib_offsets"]) < 50:
492 result["missed_zlib_offsets"].append(at)
493 q = mt.start() + 1
494 p += len(piece)
495
496
497def _expected_shards(start, end, shard_size):
498 out = []
499 index = 0
500 pos = start
501 while pos < end:
502 stop = min(end, pos + shard_size)
503 out.append({"index": index, "start": pos, "end": stop})
504 index += 1
505 pos = stop
506 return out
507
508
509def _shard_path(outdir, want):
510 return os.path.join(outdir, "shard_%03d_%d_%d.json" % (want["index"], want["start"], want["end"]))
511
512
513def _shard_ok(path, want):
514 try:
515 with open(path, encoding="utf-8") as f:
516 doc = json.load(f)
517 except (OSError, ValueError):
518 return False
519 return (doc.get("format") == FORMAT and doc.get("start") == want["start"]
520 and doc.get("end") == want["end"] and doc.get("complete") is True)
521
522
523def _load_shards(outdir, expected):
524 docs = {}
525 for want in expected:
526 path = _shard_path(outdir, want)
527 if _shard_ok(path, want):
528 with open(path, encoding="utf-8") as f:
529 docs[want["index"]] = json.load(f)
530 return docs
531
532
533def _duplicates(rows):
534 by_hash = {}
535 for r in rows:
536 by_hash.setdefault(r["sha1"], []).append(r)
537 groups = [v for v in by_hash.values() if len(v) > 1]
538 extra = sum(len(v) - 1 for v in groups)
539 extra_entities = sum(sum(x["entities"] for x in v[1:]) for v in groups)
540 by_name = {}
541 for r in rows:
542 if r.get("map_name"):
543 by_name.setdefault(r["map_name"], []).append(r)
544 ngroups = [v for v in by_name.values() if len(v) > 1]
545 return {"content_groups": len(groups), "content_extra_maps": extra,
546 "content_extra_entities": extra_entities,
547 "content_group_sample": [[v[0]["map_name"], len(v)] for v in groups[:20]],
548 "name_groups": len(ngroups), "name_extra_maps": sum(len(v) - 1 for v in ngroups)}
549
550
551def _bands(rows):
552 bands = []
553 for r in sorted(rows, key=lambda x: x["offset"]):
554 if bands and r["offset"] - bands[-1]["last_end"] <= BAND_GAP:
555 bands[-1]["last_end"] = max(bands[-1]["last_end"], r["offset"] + r["stored"])
556 bands[-1]["maps"] += 1
557 bands[-1]["entities"] += r["entities"]
558 else:
559 bands.append({"first": r["offset"], "last_end": r["offset"] + r["stored"],
560 "maps": 1, "entities": r["entities"]})
561 return bands
562
563
564def summarize(archive, outdir, start, end, shard_size, data_start):
565 expected = _expected_shards(start, end, shard_size)
566 docs = _load_shards(outdir, expected)
567 missing = [w for w in expected if w["index"] not in docs]
568 rows, intervals, raw_pages, raw_system = [], [], [], []
569 totals = {"streams": 0, "stored": 0, "raw_system": 0, "inflated": 0, "rejected": 0, "meta": 0,
570 "map_meta": 0, "meta_other": 0, "map_meta_bytes": 0,
571 "invalid": 0, "incomplete": 0, "join_max": 0, "entity_gfx": 0,
572 "entity_unresolved": 0, "adopted": 0}
573 shards = []
574 for want in expected:
575 doc = docs.get(want["index"])
576 if doc is None:
577 shards.append({**want, "present": False})
578 continue
579 shards.append({"index": want["index"], "start": want["start"], "end": want["end"],
580 "present": True, "elapsed": doc.get("elapsed"),
581 "maps": len(doc.get("rows", [])),
582 "entities": sum(r["entities"] for r in doc.get("rows", [])),
583 "map_first": doc.get("map_first"), "map_last": doc.get("map_last"),
584 "stats": doc.get("stats", {})})
585 rows.extend(doc.get("rows", []))
586 intervals.extend(doc.get("intervals", []))
587 raw_pages.extend(doc.get("raw_pages", []))
588 raw_system.extend(doc.get("raw_system", []))
589 for k in totals:
590 if k == "join_max":
591 totals[k] = max(totals[k], doc.get("stats", {}).get(k, 0))
592 else:
593 totals[k] += doc.get("stats", {}).get(k, 0)
594 seen = set()
595 unique = []
596 duplicate_offsets = 0
597 for r in sorted(rows, key=lambda x: x["offset"]):
598 if r["offset"] in seen:
599 duplicate_offsets += 1
600 continue
601 seen.add(r["offset"])
602 unique.append(r)
603 rows = unique
604 gaps = classify_gaps(archive, intervals, raw_pages, raw_system, start, end)
605 exact_maps = sum(1 for r in rows if r.get("exact"))
606 exact_entities = sum(r["entities"] for r in rows if r.get("exact"))
607 summary = {
608 "archive": os.path.abspath(archive), "archive_size": os.path.getsize(archive),
609 "data_start": data_start, "scan_start": start, "scan_end": end,
610 "span": end - start, "shards_expected": len(expected), "shards_complete": len(docs),
611 "complete": not missing, "missing_ranges": [[m["start"], m["end"]] for m in missing],
612 "elapsed_shard_sum": round(sum(d.get("elapsed", 0) for d in docs.values()), 3),
613 "maps": len(rows), "maps_exact": exact_maps,
614 "entities": sum(r["entities"] for r in rows),
615 "entities_exact": exact_entities,
616 "duplicate_offsets": duplicate_offsets,
617 "map_first": rows[0]["offset"] if rows else None,
618 "map_last": rows[-1]["offset"] if rows else None,
619 "totals": totals, "duplicates": _duplicates(rows),
620 "bands": _bands(rows), "coverage": gaps, "shards": shards,
621 }
622 summary["census_exact"] = (summary["complete"] and summary["maps_exact"] == summary["maps"]
623 and totals["entity_gfx"] == 0 and totals["entity_unresolved"] == 0
624 and gaps["raw_maps"] == 0 and gaps["missed_zlib_meta"] == 0)
625 return summary
626
627
628def main(argv=None):
629 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
630 ap.add_argument("archive")
631 ap.add_argument("--out", default=os.path.join("work", "world", "census"))
632 ap.add_argument("--shard-size", type=int, default=2 << 30)
633 ap.add_argument("--jobs", type=int, default=max(1, min(12, (os.cpu_count() or 2) // 2)))
634 ap.add_argument("--start", type=int)
635 ap.add_argument("--limit", type=int)
636 ap.add_argument("--resume", action="store_true")
637 ap.add_argument("--merge-only", action="store_true")
638 a = ap.parse_args(argv)
639 with open(a.archive, "rb") as f:
640 head = f.read(8)
641 if head[:4] != b"9FPR":
642 print("not an RPF9 archive", file=sys.stderr)
643 return 2
644 data_start = struct.unpack_from("<I", head, 4)[0]
645 size = os.path.getsize(a.archive)
646 start = a.start if a.start is not None else data_start
647 end = min(size, start + a.limit) if a.limit else size
648 if start < data_start or start >= end:
649 print("bad scan range", file=sys.stderr)
650 return 2
651 os.makedirs(a.out, exist_ok=True)
652 expected = _expected_shards(start, end, a.shard_size)
653 t0 = time.time()
654 if not a.merge_only:
655 jobs = []
656 for want in expected:
657 path = _shard_path(a.out, want)
658 if a.resume and _shard_ok(path, want):
659 continue
660 jobs.append((a.archive, want["index"], want["start"], want["end"], a.out, data_start))
661 print("census: %d shards, %d to scan, %d jobs, %.2f GiB" %
662 (len(expected), len(jobs), a.jobs, (end - start) / (1 << 30)), flush=True)
663 failures = 0
664 with ProcessPoolExecutor(max_workers=a.jobs) as ex:
665 futures = {ex.submit(scan_shard, job): job for job in jobs}
666 for done, fut in enumerate(as_completed(futures), 1):
667 job = futures[fut]
668 try:
669 r = fut.result()
670 except Exception as e: # keep completed shards; the rerun resumes them
671 failures += 1
672 print("[%d/%d] shard %d FAILED: %r" % (done, len(jobs), job[1], e), flush=True)
673 continue
674 print("[%d/%d] shard %03d %d..%d maps=%d entities=%d %.1fs" %
675 (done, len(jobs), r["index"], r["start"], r["end"], r["maps"],
676 r["entities"], r["elapsed"]), flush=True)
677 if failures:
678 print("%d shard(s) failed; writing the completed coverage" % failures, flush=True)
679 summary = summarize(a.archive, a.out, start, end, a.shard_size, data_start)
680 summary["elapsed"] = round(time.time() - t0, 3)
681 with open(os.path.join(a.out, "summary.json"), "w", encoding="utf-8") as f:
682 json.dump(summary, f, indent=1, sort_keys=True)
683 with open(os.path.join(a.out, "maps.json"), "w", encoding="utf-8") as f:
684 json.dump({"summary": {k: summary[k] for k in
685 ("maps", "maps_exact", "entities", "entities_exact", "scan_start",
686 "scan_end", "complete", "census_exact")},
687 "maps": [r for d in _load_shards(a.out, expected).values() for r in d.get("rows", [])]},
688 f, indent=1, sort_keys=True)
689 print(json.dumps({k: summary[k] for k in
690 ("maps", "maps_exact", "entities", "entities_exact", "complete", "census_exact",
691 "shards_complete", "shards_expected", "elapsed", "coverage", "duplicates")},
692 indent=1), flush=True)
693 return 0 if summary["complete"] else 1
694
695
696if __name__ == "__main__":
697 sys.exit(main())