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:
authorVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 19:07:53 +0100
committerVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 19:07:53 +0100
commit46a196cde9328e2a232ee15c19556eb962cda0ab (patch)
treed1cd03326530912d925ee1a7ba7fa735006f004f /tools
parentd3fab00a78967adf357596996190afdf33dc09d5 (diff)
parentec8ec4c9a46c6623f1a9c125afd3566da97f1e0c (diff)
Merge upstream main into first-light shader identity
Diffstat (limited to 'tools')
-rw-r--r--tools/analyze_4240_full.py34
-rw-r--r--tools/anim_glb.py738
-rw-r--r--tools/anim_index.py42
-rw-r--r--tools/anim_rigs.py19
-rw-r--r--tools/audio_wav.py43
-rw-r--r--tools/awc_manifest.py12
-rw-r--r--tools/awc_names.py25
-rw-r--r--tools/awc_opus.py11
-rw-r--r--tools/batch_glb.py208
-rw-r--r--tools/bcpack_tool.py243
-rw-r--r--tools/bink_names.py52
-rw-r--r--tools/buffer_store_probe.py336
-rw-r--r--tools/buffer_swizzle_probe.py665
-rw-r--r--tools/bvh_rehydrate.py480
-rw-r--r--tools/content_definitions.py226
-rw-r--r--tools/cpu_ref.py4
-rw-r--r--tools/d16_format_probe.py19
-rw-r--r--tools/dds_png.py39
-rw-r--r--tools/ds_permute_probe.py193
-rw-r--r--tools/f16_trans_sweep.py54
-rw-r--r--tools/f32_fuzz.py19
-rw-r--r--tools/first_light.py18
-rw-r--r--tools/fssm_unpack.py28
-rw-r--r--tools/gamedata_index.py46
-rw-r--r--tools/gamedata_maps.py158
-rw-r--r--tools/gamedata_reader.py279
-rw-r--r--tools/gamedata_xml.py50
-rw-r--r--tools/gen_d3d12_stubs.py43
-rw-r--r--tools/glb_writer.py14
-rw-r--r--tools/hw_oracle/tsharp.py2
-rw-r--r--tools/image_d16_probe.py315
-rw-r--r--tools/image_query_probe.py307
-rw-r--r--tools/instance_lists.py13
-rw-r--r--tools/int_hw_probe.py18
-rw-r--r--tools/lane_masks.py36
-rw-r--r--tools/manifest.py11
-rw-r--r--tools/manifest_verifier.py2
-rw-r--r--tools/mesh_compute_vs.py16
-rw-r--r--tools/meshlet_page.py8
-rw-r--r--tools/mode_round_probe.py189
-rw-r--r--tools/navmesh_decode.py22
-rw-r--r--tools/navmesh_index.py13
-rw-r--r--tools/opus_tags.py28
-rw-r--r--tools/pe_inspect.py22
-rw-r--r--tools/pe_shader_containers.py39
-rw-r--r--tools/psin_names.py22
-rw-r--r--tools/rbf0_tree.py15
-rw-r--r--tools/rdna2spirv.py797
-rw-r--r--tools/report_paths.py50
-rw-r--r--tools/restofworld_index.py30
-rw-r--r--tools/root_sig_contract.py8
-rw-r--r--tools/rpf9_carve.py107
-rw-r--r--tools/rpf9dump/rpf9dump.csproj2
-rw-r--r--tools/rpf_probe.py15
-rw-r--r--tools/rtti_scan.py4
-rw-r--r--tools/salu_diff.py28
-rw-r--r--tools/save_keys.py9
-rw-r--r--tools/sdwa_diff.py779
-rw-r--r--tools/shader_disasm.py22
-rw-r--r--tools/shader_ir.py6
-rw-r--r--tools/shader_stage_manifest.py20
-rw-r--r--tools/skin_streams.py11
-rw-r--r--tools/skinned_glb.py938
-rw-r--r--tools/spirv_asm.py467
-rw-r--r--tools/spirv_asm_tables.py1047
-rw-r--r--tools/spirv_metal_set0.py40
-rw-r--r--tools/tex_export.py8
-rw-r--r--tools/texoff_probe.py164
-rw-r--r--tools/text_tables.py9
-rw-r--r--tools/tile_probe.py13
-rw-r--r--tools/user_sgpr_census.py52
-rw-r--r--tools/valu_fuzz.py5
-rw-r--r--tools/wave64_halves.py93
-rw-r--r--tools/world_build.py6
-rw-r--r--tools/world_lights_paths.py21
-rw-r--r--tools/world_names.py24
-rw-r--r--tools/xdxr_bvh.py6
77 files changed, 9398 insertions, 559 deletions
diff --git a/tools/analyze_4240_full.py b/tools/analyze_4240_full.py
index e5b6f50e3..032302246 100644
--- a/tools/analyze_4240_full.py
+++ b/tools/analyze_4240_full.py
@@ -297,6 +297,16 @@ def positive_int(text):
297 return value 297 return value
298 298
299 299
300def same_output_path(first, second):
301 """True when the two names are one file: the same path, or a link, junction or other spelling of it."""
302 if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)):
303 return True
304 try:
305 return os.path.samefile(first, second)
306 except OSError:
307 return False
308
309
300def main() -> int: 310def main() -> int:
301 parser = argparse.ArgumentParser(description="Analyze 42 40 00 00 vertex blocks in RPF9 archives") 311 parser = argparse.ArgumentParser(description="Analyze 42 40 00 00 vertex blocks in RPF9 archives")
302 parser.add_argument("inputs", nargs="+", help="RPF9 archive paths") 312 parser.add_argument("inputs", nargs="+", help="RPF9 archive paths")
@@ -304,7 +314,17 @@ def main() -> int:
304 parser.add_argument("--limit", type=positive_int, help="Limit streams per archive") 314 parser.add_argument("--limit", type=positive_int, help="Limit streams per archive")
305 parser.add_argument("--verbose", "-v", action="store_true") 315 parser.add_argument("--verbose", "-v", action="store_true")
306 args = parser.parse_args() 316 args = parser.parse_args()
307 317 # Checked before the scan: the report is written after every archive has been read, so a --json naming one of
318 # them replaced the archive with the report, and a folder only failed once the whole scan was done.
319 if args.json:
320 if os.path.isdir(args.json):
321 print(f"ERROR: --json {args.json} is a folder, not a file", file=sys.stderr)
322 return 2
323 for path in args.inputs:
324 if same_output_path(args.json, path):
325 print(f"ERROR: --json {args.json} would overwrite the input archive {path}", file=sys.stderr)
326 return 2
327
308 all_stats, status = [], 0 328 all_stats, status = [], 0
309 for path in args.inputs: 329 for path in args.inputs:
310 if not os.path.exists(path): 330 if not os.path.exists(path):
@@ -350,10 +370,14 @@ def main() -> int:
350 s_copy["slot_tag_counts"] = {str(k): v for k, v in s["slot_tag_counts"].items()} 370 s_copy["slot_tag_counts"] = {str(k): v for k, v in s["slot_tag_counts"].items()}
351 output.append(s_copy) 371 output.append(s_copy)
352 parent = os.path.dirname(os.path.abspath(args.json)) 372 parent = os.path.dirname(os.path.abspath(args.json))
353 if parent: # every archive has been read by now; a missing folder used to lose the run 373 try:
354 os.makedirs(parent, exist_ok=True) 374 if parent: # every archive has been read by now; a missing folder used to lose the run
355 with open(args.json, "w", encoding="utf-8", newline="\n") as f: 375 os.makedirs(parent, exist_ok=True)
356 json.dump(output, f, indent=2) 376 with open(args.json, "w", encoding="utf-8", newline="\n") as f:
377 json.dump(output, f, indent=2)
378 except OSError as e:
379 print(f"ERROR: cannot write {args.json}: {e.strerror or e}", file=sys.stderr)
380 return 2
357 return status 381 return status
358 382
359 383
diff --git a/tools/anim_glb.py b/tools/anim_glb.py
new file mode 100644
index 000000000..9fda12044
--- /dev/null
+++ b/tools/anim_glb.py
@@ -0,0 +1,738 @@
1"""Export a skinned character part with its skeleton and decoded clips as an animated binary glTF (.glb).
2
3Three readers meet here: the skeleton that a character fragment carries at drawable + 0x18, the skin streams of
4a part drawable (docs/character_skeleton.md, ASSET-12) and the clip dictionaries of anim.rpf (anim_clips.py). Each
5part mesh is bound to the skeleton through its model's bone list, and each clip track to a skeleton joint through
6its bone hash. Nothing is invented: a part whose weighted bones are not in the skeleton is refused, and clip tracks
7that name no joint are counted and left out.
8
9Skeleton (measured on the 596-bone female and 560-bone male humanoid fragments of packs.rpf):
10
11 header = drawable + 0x18 +0x28 bone records, +0x30 inverse bind matrices (64 bytes each),
12 +0x40 u16 parent indices (0xFFFF = root), +0x6C/+0x6E u16 bone count
13 bone record (0x50 bytes) +0x00 rotation quaternion (x, y, z, w), +0x10 translation (x, y, z),
14 +0x1C u32 joaat32(lowercase bone name), +0x20 scale (x, y, z),
15 +0x30 name pointer, +0x46 u16 parent, +0x48 u16 own index
16
17The default rotation, translation and scale are local to the parent. Composed down the hierarchy they give each
18joint's model-space transform, and its inverse is the stored inverse bind matrix (the check is in `read_skeleton`).
19The matrices are row-vector (D3D) matrices; stored row by row, they are glTF's column-major layout as is.
20
21Part meshes: grmModel + 0x14 u16 bone count, grmModel + 0x28 pointer to that many u32 bone hashes (joaat32 of the
22bone names). A vertex's bone indices (FVF semantics 20/21) index this list; its weights are the UNORM bytes of
23semantics 16/17 (they sum to 255). Positions and the clustered index buffer are read as rpf9-explorer reads them.
24
25Clips: a `.clip` lists animations, each played over its own [start, end] window at its rate. A track is
26{joaat32(bone name), track type, format}: `bonerotation` (quaternion), `bonetranslation` (vec3) and `bonescale`
27(vec3) drive the joint with that hash, and bone hash 0 is the mover (root motion), which drives an extra node
28above the skeleton. Other track types (`genericcontrol`, facial, camera) are counted, not exported.
29
30The skeleton, meshes and clips stay in RAGE's Z-up space; one root node turns it into glTF's Y-up.
31
32Usage:
33 python -I anim_glb.py <archive.rpf> <out.glb> --skeleton <offset> --part <offset>[:<child>] [--part ...]
34 [--anim <anim.rpf> --dictionary <offset> [--clip <name or 0xhash> ...]]
35 [--lod N] [--max-influences 4|8] [--no-root-motion] [--report <out.json>]
36 python -I anim_glb.py --coverage <archive.rpf> --skeleton <offset> --anim <anim.rpf> --report <out.json>
37 [--jobs N]
38
39Offsets are the resources' zlib stream offsets in the archive (the `0x...` offsets rpf9dump and skin_streams
40report). `--part` takes a drawable, a fragment or a drawable dictionary; `:<child>` picks a dictionary child.
41`--coverage` writes counts only: how many clip-dictionary bone tracks name a joint of the skeleton.
42"""
43import argparse
44import collections
45import json
46import math
47import mmap
48import os
49import struct
50import sys
51import time
52import zlib
53
54# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling readers.
55sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
56
57import anim_clips # noqa: E402
58import anim_index # noqa: E402
59import glb_writer # noqa: E402
60import skin_streams # noqa: E402
61
62SYSTEM = 0x50000000
63GRAPHICS = 0x60000000
64MAX_BONES = 4096
65BONE_STRIDE = 0x50
66WEIGHT_SLOTS = (16, 17)
67INDEX_SLOTS = (20, 21)
68# (element bytes, format byte) of the bone-index slots, as skin_streams measures them
69INDEX_LAYOUTS = {(4, 30): "u8x4", (16, 3): "packed", (8, 12): "u16x4", (1, 62): "rigid-u8", (2, 57): "rigid-u16"}
70TRACK_PATHS = {anim_index.joaat32("bonerotation"): "rotation", anim_index.joaat32("bonetranslation"): "translation",
71 anim_index.joaat32("bonescale"): "scale"}
72PATH_FORMATS = {"rotation": 0, "translation": 2, "scale": 2}
73Z_UP_TO_Y_UP = [-math.sqrt(0.5), 0.0, 0.0, math.sqrt(0.5)] # -90 degrees about X: (x, y, z) -> (x, z, -y)
74COMPONENT_UNSIGNED_SHORT = 5123
75COMPONENT_FLOAT = 5126
76
77
78class ExportError(ValueError):
79 """The input is not what the exporter reads; the message says which check failed."""
80
81
82def require(condition, message):
83 if not condition:
84 raise ExportError(message)
85
86
87def u16(b, o):
88 return struct.unpack_from("<H", b, o)[0]
89
90
91def u32(b, o):
92 return struct.unpack_from("<I", b, o)[0]
93
94
95def u64(b, o):
96 return struct.unpack_from("<Q", b, o)[0]
97
98
99def sys_at(b, field, size, what):
100 """A system pointer field resolved to an offset in the system pages, with `size` bytes in range."""
101 p = u64(b, field)
102 require(SYSTEM <= p < GRAPHICS, f"{what}: not a system pointer")
103 off = p - SYSTEM
104 require(off + size <= len(b), f"{what}: points past the system pages")
105 return off
106
107
108def gfx_at(sys, gfx, field, size, what):
109 p = u64(sys, field)
110 require(GRAPHICS <= p < GRAPHICS + 0x10000000, f"{what}: not a graphics pointer")
111 off = p - GRAPHICS
112 require(off + size <= len(gfx), f"{what}: points past the graphics pages")
113 return off
114
115
116def c_string(b, field):
117 p = u64(b, field)
118 if not SYSTEM <= p < GRAPHICS or p - SYSTEM >= len(b):
119 return None
120 at = p - SYSTEM
121 end = b.find(b"\0", at, at + 256)
122 if end < 0:
123 return None
124 return b[at:end].decode("latin-1")
125
126
127# ---------------------------------------------------------------- resources
128
129
130def load_resource(m, at):
131 """(system pages, graphics pages) of the resource whose first zlib stream starts at `at`."""
132 size = len(m)
133 require(0 <= at < size, f"offset 0x{at:x} is outside the archive")
134 data, used = skin_streams.inflate_at(m, at, size)
135 require(data is not None and len(data) >= 192, f"no resource stream at 0x{at:x}")
136 directory = sys_at(data, 8, 16, "page directory")
137 system_pages, graphics_pages = data[directory + 8], data[directory + 9]
138 require(0 < system_pages <= 32 and graphics_pages <= 32, "page directory counts")
139 parts, fp = [data], at + used
140 for _ in range(system_pages - 1 + graphics_pages):
141 nxt = skin_streams.next_stream(m, fp, size)
142 require(nxt is not None, "a page stream of the resource is missing")
143 parts.append(nxt[0])
144 fp = nxt[1] + nxt[2]
145 return b"".join(parts[:system_pages]), b"".join(parts[system_pages:])
146
147
148def drawable_at(sys, child):
149 """System offset of the drawable to read: a dictionary child, a fragment's drawable or the drawable itself."""
150 kind = skin_streams.resource_kind(sys)
151 require(kind is not None, "not a drawable, fragment or drawable dictionary")
152 found = list(skin_streams.drawable_offsets(sys, kind))
153 if child is None:
154 require(len(found) == 1, f"{kind} with {len(found)} drawables: pick one with :<child>")
155 child = 0
156 require(0 <= child < len(found), f"child {child} is not in 0..{len(found) - 1}")
157 return found[child]
158
159
160# ---------------------------------------------------------------- skeleton
161
162
163def quat_mul(a, b):
164 ax, ay, az, aw = a
165 bx, by, bz, bw = b
166 return (aw * bx + ax * bw + ay * bz - az * by, aw * by - ax * bz + ay * bw + az * bx,
167 aw * bz + ax * by - ay * bx + az * bw, aw * bw - ax * bx - ay * by - az * bz)
168
169
170def quat_rotate(q, v):
171 x, y, z, w = q
172 vx, vy, vz = v
173 tx, ty, tz = 2 * (y * vz - z * vy), 2 * (z * vx - x * vz), 2 * (x * vy - y * vx)
174 return (vx + w * tx + y * tz - z * ty, vy + w * ty + z * tx - x * tz, vz + w * tz + x * ty - y * tx)
175
176
177def read_skeleton(sys, drawable):
178 """-> list of joints {hash, name, parent, rotation, translation, scale, inverse_bind (16 floats)}.
179
180 Also returns the largest distance between a joint's model-space position composed from the default
181 transforms and the one its inverse bind matrix gives; `export` refuses a skeleton where they disagree."""
182 header = sys_at(sys, drawable + 0x18, 0x70, "skeleton")
183 count = u16(sys, header + 0x6C)
184 require(0 < count <= MAX_BONES and count == u16(sys, header + 0x6E), "skeleton bone count")
185 records = sys_at(sys, header + 0x28, count * BONE_STRIDE, "bone records")
186 inverse = sys_at(sys, header + 0x30, count * 64, "inverse bind matrices")
187 parents = sys_at(sys, header + 0x40, count * 2, "parent indices")
188 joints = []
189 for i in range(count):
190 r = records + i * BONE_STRIDE
191 parent = u16(sys, parents + 2 * i)
192 require(u16(sys, r + 0x48) == i and u16(sys, r + 0x46) == parent, f"bone record {i} index/parent")
193 require(parent == 0xFFFF or parent < i, f"bone {i} parent {parent} is not an earlier bone")
194 m = struct.unpack_from("<16f", sys, inverse + 64 * i)
195 require(all(math.isfinite(v) for v in m) and m[3] == m[7] == m[11] == 0, f"inverse bind matrix {i}")
196 joints.append({
197 "hash": u32(sys, r + 0x1C), "name": c_string(sys, r + 0x30), "parent": None if parent == 0xFFFF else parent,
198 "rotation": struct.unpack_from("<4f", sys, r), "translation": struct.unpack_from("<3f", sys, r + 0x10),
199 "scale": struct.unpack_from("<3f", sys, r + 0x20), "inverse_bind": list(m[:15]) + [1.0],
200 })
201 # Compose the default transforms; compare each joint's origin with the one its inverse bind matrix gives.
202 world, worst = [], 0.0
203 for j in joints:
204 q, t = j["rotation"], j["translation"]
205 if j["parent"] is None:
206 world.append((q, t))
207 else:
208 pq, pt = world[j["parent"]]
209 world.append((quat_mul(pq, q), tuple(a + b for a, b in zip(pt, quat_rotate(pq, t)))))
210 m = j["inverse_bind"]
211 rows, t_inv = (m[0:3], m[4:7], m[8:11]), m[12:15]
212 origin = tuple(-sum(t_inv[k] * rows[c][k] for k in range(3)) for c in range(3))
213 worst = max(worst, max(abs(a - b) for a, b in zip(origin, world[-1][1])))
214 return joints, worst
215
216
217# ---------------------------------------------------------------- part meshes
218
219
220def read_positions(sys, gfx, vb, fvf, vertices):
221 offset, size, fmt = u32(sys, fvf), sys[fvf + 0xD0], sys[fvf + 0x104]
222 length = u32(sys, vb + 8) * u16(sys, vb + 12)
223 require(length > 0 and 96 <= offset <= length and size * vertices <= length - offset, "position stream bounds")
224 at = gfx_at(sys, gfx, vb + 24, length, "vertex buffer")
225 data = gfx[at:at + length]
226 if (size, fmt) == (12, 6):
227 require(u32(data, 0) & 127 == 0x63, "float position descriptor")
228 return [struct.unpack_from("<3f", data, offset + 12 * i) for i in range(vertices)], data
229 if (size, fmt) == (8, 16):
230 require(offset >= 128 and u32(data, 0) & 127 == 0x42, "quantized position descriptor")
231 bias, scale = struct.unpack_from("<3f", data, 96), struct.unpack_from("<3f", data, 112)
232 axis = u32(data, 108)
233 require(axis <= 2 and min(scale) >= 0, "quantized position bias/scale")
234 out = []
235 for i in range(vertices):
236 q = u64(data, offset + 8 * i)
237 p = (bias[0] + scale[0] * ((q >> 8) & 0xFFFFFF), bias[1] + scale[1] * ((((q >> 32) & 0xFFFF) << 8) | (q & 0xFF)),
238 bias[2] + scale[2] * (q >> 48))
239 out.append((p[2], p[1], p[0]) if axis == 0 else (p[1], p[2], p[0]) if axis == 1 else p)
240 return out, data
241 raise ExportError(f"position encoding {size}/{fmt} is not read")
242
243
244def read_triangles(sys, gfx, geometry, vertices):
245 """The clustered index buffer: cluster records, 7-bit corner triplets, then the vertex reference list."""
246 descriptor = sys_at(sys, geometry + 64, 16, "index descriptor")
247 ib = sys_at(sys, descriptor, 64, "index buffer")
248 require(u16(sys, ib + 12) == 4, "index buffer stride")
249 length = u32(sys, ib + 8) * 4
250 at = gfx_at(sys, gfx, ib + 24, length, "index data")
251 data = gfx[at:at + length]
252 count_flags = u32(data, 0)
253 palette = count_flags & 0x40000000
254 clusters = count_flags & (0xFFFF if palette else 0x7FFFFFFF)
255 triangles, refs = u32(data, 4), u32(data, 8)
256 require(0 < clusters <= 2048 and 0 < triangles <= 65535 and 0 < refs <= 65535, "index buffer counts")
257 ref_size = 2 if count_flags & 0x80000000 else 4
258 tri_at = 12 + clusters * 16
259 refs_at = tri_at + triangles * 4
260 require(refs_at + refs * ref_size <= length, "index buffer length")
261 fmt = "<%d%s" % (refs, "H" if ref_size == 2 else "I")
262 references = struct.unpack_from(fmt, data, refs_at)
263 require(max(references) < vertices, "vertex reference past the vertex count")
264 indices, seen_refs, seen_tris = [], 0, 0
265 for c in range(clusters):
266 packed, offsets = u32(data, 12 + 16 * c), u32(data, 16 + 16 * c)
267 n_vertices, n_tris = (packed & 127) + 1, ((packed >> 7) & 255) + 1
268 v_start, t_start = offsets & 0xFFFF, offsets >> 16
269 require(v_start == seen_refs and t_start == seen_tris, "cluster starts (meshes over 65,535 are not read)")
270 for t in range(t_start, t_start + n_tris):
271 word = u32(data, tri_at + 4 * t)
272 require(word >> 21 == c, "triangle cluster tag")
273 for corner in range(3):
274 local = (word >> (7 * corner)) & 127
275 require(local < n_vertices, "triangle corner past its cluster")
276 indices.append(references[v_start + local])
277 seen_refs += n_vertices
278 seen_tris += n_tris
279 require(seen_refs == refs and seen_tris == triangles, "clusters do not cover the index buffer")
280 constant = count_flags & 0x20000000
281 hint = (count_flags >> 16) & 0x1FFF
282 return indices, (hint // 2 if palette and constant else None)
283
284
285def read_skin(sys, fvf, data, vertices, constant_bone):
286 """Per vertex: up to 8 (model bone index, weight 0..255) pairs with a non-zero weight."""
287 slots = {}
288 for i in WEIGHT_SLOTS + INDEX_SLOTS:
289 size = sys[fvf + 0xD0 + i]
290 if size:
291 offset = u32(sys, fvf + 4 * i)
292 require(offset + size * vertices <= len(data), f"skin slot {i} bounds")
293 slots[i] = (size, sys[fvf + 0x104 + i], offset)
294 index_slots = [i for i in INDEX_SLOTS if i in slots]
295 if not index_slots:
296 require(constant_bone is not None, "mesh has no bone-index stream and no constant binding")
297 return [[(constant_bone, 255)] for _ in range(vertices)], "constant"
298 layout = INDEX_LAYOUTS.get(slots[index_slots[0]][:2])
299 require(layout is not None and all(slots[i][:2] == slots[index_slots[0]][:2] for i in index_slots),
300 "bone-index stream format")
301 weight_slots = [i for i in WEIGHT_SLOTS if i in slots]
302 require(all(slots[i][:2] == (4, 28) for i in weight_slots), "weight stream format")
303 if layout.startswith("rigid"):
304 require(not weight_slots, "rigid index stream with weights")
305 size, _fmt, offset = slots[index_slots[0]]
306 code = "B" if size == 1 else "H"
307 return [[(v, 255)] for v in struct.unpack_from(f"<{vertices}{code}", data, offset)], layout
308 require(len(weight_slots) == len(index_slots), "weight and index stream counts differ")
309 out = []
310 for v in range(vertices):
311 pairs = []
312 for wi, ii in zip(weight_slots, index_slots):
313 weights = data[slots[wi][2] + 4 * v:slots[wi][2] + 4 * v + 4]
314 at = slots[ii][2]
315 if layout == "u8x4":
316 bones = data[at + 4 * v:at + 4 * v + 4]
317 elif layout == "u16x4":
318 bones = struct.unpack_from("<4H", data, at + 8 * v)
319 else: # packed: bits 0..11 of each u32
320 bones = [w & 0xFFF for w in struct.unpack_from("<4I", data, at + 16 * v)]
321 pairs.extend((b, w) for b, w in zip(bones, weights) if w)
322 out.append(pairs)
323 return out, layout
324
325
326def read_part(sys, gfx, drawable, lod=0):
327 """-> list of meshes {model, geometry, positions, indices, skin [(model bone, weight)], palette [hash], layout}."""
328 lod_field = drawable + 80 + 8 * lod
329 require(0 <= lod < 4 and u64(sys, lod_field), f"LOD {lod} is empty")
330 lod_at = sys_at(sys, lod_field, 16, "LOD")
331 models = u16(sys, lod_at + 8)
332 require(0 < models <= 256 and models == u16(sys, lod_at + 10), "LOD model count")
333 model_list = sys_at(sys, lod_at, models * 8, "model list")
334 meshes = []
335 for mi in range(models):
336 model = sys_at(sys, model_list + 8 * mi, 56, "model")
337 count, bones = u16(sys, model + 16), u16(sys, model + 20)
338 require(0 < count <= 256 and count == u16(sys, model + 18) == u16(sys, model + 54), "geometry count")
339 require(0 < bones <= MAX_BONES, f"model {mi} has no bone list (not skinned)")
340 palette_at = sys_at(sys, model + 0x28, bones * 4, "model bone list")
341 palette = list(struct.unpack_from(f"<{bones}I", sys, palette_at))
342 geometries = sys_at(sys, model + 8, count * 8, "geometry list")
343 for gi in range(count):
344 geometry = sys_at(sys, geometries + 8 * gi, 160, "geometry")
345 vb = sys_at(sys, geometry + 8, 80, "vertex buffer header")
346 fvf = sys_at(sys, vb + 64, 0x13C, "FVF table")
347 flags = u32(sys, fvf + 0x138)
348 vertices = flags >> 10
349 require(flags & 1 and 0 < vertices <= 1_000_000, "vertex count")
350 positions, data = read_positions(sys, gfx, vb, fvf, vertices)
351 indices, constant_bone = read_triangles(sys, gfx, geometry, vertices)
352 skin, layout = read_skin(sys, fvf, data, vertices, constant_bone)
353 for pairs in skin:
354 for b, _w in pairs:
355 require(b < bones, "weighted bone index past the model's bone list")
356 meshes.append({"model": mi, "geometry": gi, "positions": positions, "indices": indices, "skin": skin,
357 "palette": palette, "layout": layout})
358 return meshes
359
360
361def bind_part(meshes, joints, max_influences=8):
362 """Model bone index -> skeleton joint index through the bone hashes; -> per mesh JOINTS/WEIGHTS sets.
363
364 With `max_influences` 4, a vertex keeps its four largest weights, renormalised, in one set (three.js and
365 other viewers read only JOINTS_0/WEIGHTS_0)."""
366 by_hash = {}
367 for i, j in enumerate(joints):
368 by_hash[j["hash"]] = i if j["hash"] not in by_hash else -1
369 for mesh in meshes:
370 mapping = [by_hash.get(h) for h in mesh["palette"]]
371 missing = {mesh["palette"][b] for pairs in mesh["skin"] for b, _w in pairs if mapping[b] is None or mapping[b] < 0}
372 require(not missing, "weighted bones not in the skeleton: " + ", ".join(f"0x{h:08x}" for h in sorted(missing)))
373 sets = 2 if max_influences > 4 and max((len(p) for p in mesh["skin"]), default=0) > 4 else 1
374 joint_rows, weight_rows = [], []
375 for pairs in mesh["skin"]:
376 pairs = sorted(pairs, key=lambda p: -p[1])[:4 * sets]
377 total = float(sum(w for _b, w in pairs))
378 require(total > 0, "vertex with no weight")
379 row_j = [mapping[b] for b, _w in pairs] + [0] * (4 * sets - len(pairs))
380 row_w = [w / total for _b, w in pairs] + [0.0] * (4 * sets - len(pairs))
381 joint_rows.append(row_j)
382 weight_rows.append(row_w)
383 mesh["joints"], mesh["weights"], mesh["sets"] = joint_rows, weight_rows, sets
384 return meshes
385
386
387# ---------------------------------------------------------------- clips
388
389
390def load_dictionary(path, offset):
391 """Parse the clip dictionary whose root stream starts at `offset` -> (System, dictionary)."""
392 rows, _walk = anim_index.scan_rpf(path, offset, 64 << 20)
393 with open(path, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m:
394 groups, _unresolved, _gaps = anim_clips.group(m, rows[:4])
395 require(groups and rows[groups[0][0]]["offset"] == offset, f"no clip dictionary starts at 0x{offset:x}")
396 data = b""
397 with open(path, "rb") as fh:
398 for k in groups[0][1]:
399 off, stored, raw = anim_clips.segment(rows, k)
400 fh.seek(off)
401 data += fh.read(stored) if raw else zlib.decompressobj().decompress(fh.read(stored))
402 s = anim_clips.System(data)
403 return s, anim_clips.parse_dictionary(s)
404
405
406def clip_label(clip):
407 name = clip.get("name") or f"0x{clip['hash']:08x}"
408 if name.startswith("pack:/"):
409 name = name[6:]
410 return name[:-5] if name.endswith(".clip") else name
411
412
413def select_clips(dictionary, wanted):
414 clips = [c for c in dictionary["clips"] if c["kind"] == "clip"]
415 if not wanted:
416 return clips
417 out = []
418 for w in wanted:
419 hits = [c for c in clips if clip_label(c) == w or (w.lower().startswith("0x") and c["hash"] == int(w, 16))]
420 require(hits, f"clip {w!r} is not in the dictionary")
421 out.extend(hits)
422 return out
423
424
425def clip_channels(s, dictionary, clip, joint_by_hash, root_motion, tally):
426 """-> {(target, path): [(time, value)]} for one clip. target is a joint index or 'mover'."""
427 animations = {a["offset"]: a for p in dictionary["packs"] for a in p["animations"]}
428 channels = {}
429 for entry in clip["animations"]:
430 anim = animations.get(entry["animation"])
431 if anim is None:
432 tally["animations_not_local"] += 1
433 continue
434 tracks, frames = anim_clips.decode_animation(s, anim)
435 rate = entry["rate"] if entry["rate"] and math.isfinite(entry["rate"]) and entry["rate"] > 0 else 1.0
436 step = anim["duration"] / (frames - 1) if frames > 1 and anim["duration"] > 0 else 1.0 / 30
437 start = entry["start"] if math.isfinite(entry["start"]) else 0.0
438 end = entry["end"] if math.isfinite(entry["end"]) and entry["end"] > start else anim["duration"]
439 keep = [k for k in range(frames) if start - 1e-4 <= k * step <= end + 1e-4] or [0]
440 tally["animations"] += 1
441 for t, (bone, ttype, fmt) in enumerate(anim["tracks"]):
442 path = TRACK_PATHS.get(ttype)
443 if path is None:
444 tally["tracks_other_type"] += 1
445 continue
446 if fmt != PATH_FORMATS[path] or t not in tracks:
447 tally["tracks_unexpected_format"] += 1
448 continue
449 if bone == 0:
450 if not root_motion:
451 tally["tracks_mover_skipped"] += 1
452 continue
453 target = "mover"
454 else:
455 target = joint_by_hash.get(bone)
456 if target is None:
457 tally["tracks_bone_not_in_skeleton"] += 1
458 continue
459 tally["tracks_exported"] += 1
460 if (target, path) in channels:
461 tally["tracks_overridden"] += 1
462 # a frame kept by the 1e-4 tolerance before `start` would get a slightly negative time
463 channels[(target, path)] = [(max(0.0, (k * step - start) / rate), tuple(tracks[t][k])) for k in keep]
464 return channels
465
466
467# ---------------------------------------------------------------- glTF
468
469
470def _view(buf, views, payload, target=None):
471 return glb_writer._append_buffer_view(buf, views, payload, target=target)
472
473
474def _accessor(accessors, view, component, count, kind, **extra):
475 accessors.append(dict(bufferView=view, componentType=component, count=count, type=kind, **extra))
476 return len(accessors) - 1
477
478
479def _floats(values):
480 return struct.pack(f"<{len(values)}f", *values)
481
482
483def build(joints, meshes, clips, *, root_motion=True, generator="Leonida anim_glb"):
484 """glTF JSON + binary chunk for the skeleton, the bound meshes and the clip channels -> GLB bytes."""
485 buf, views, accessors = bytearray(), [], []
486 nodes = [{"name": "rage_z_up", "rotation": Z_UP_TO_Y_UP, "children": []}]
487 holder = nodes[0]
488 mover = None
489 if root_motion:
490 mover = len(nodes)
491 nodes.append({"name": "mover", "children": []})
492 holder["children"].append(mover)
493 holder = nodes[mover]
494 first_joint = len(nodes)
495 for i, j in enumerate(joints):
496 node = {"name": j["name"] or f"bone_0x{j['hash']:08x}"}
497 node["rotation"] = [round(v, 7) for v in j["rotation"]]
498 node["translation"] = [round(v, 7) for v in j["translation"]]
499 if any(abs(s - 1.0) > 1e-6 for s in j["scale"]):
500 node["scale"] = [round(v, 7) for v in j["scale"]]
501 nodes.append(node)
502 for i, j in enumerate(joints):
503 if j["parent"] is None:
504 holder["children"].append(first_joint + i)
505 else:
506 nodes[first_joint + j["parent"]].setdefault("children", []).append(first_joint + i)
507 ibm_view = _view(buf, views, _floats([v for j in joints for v in j["inverse_bind"]]))
508 ibm = _accessor(accessors, ibm_view, COMPONENT_FLOAT, len(joints), "MAT4")
509 skin = {"joints": list(range(first_joint, first_joint + len(joints))), "inverseBindMatrices": ibm}
510 roots = [first_joint + i for i, j in enumerate(joints) if j["parent"] is None]
511 if len(roots) == 1:
512 skin["skeleton"] = roots[0]
513 gltf_meshes, scene_nodes = [], [0]
514 for mesh in meshes:
515 packed = glb_writer.pack_primitive({"positions": mesh["positions"], "indices": mesh["indices"]})
516 attributes, index_accessor = glb_writer._append_packed(buf, views, accessors, packed)
517 for k in range(mesh["sets"]):
518 jv = _view(buf, views, struct.pack(f"<{4 * len(mesh['joints'])}H",
519 *[x for row in mesh["joints"] for x in row[4 * k:4 * k + 4]]),
520 target=glb_writer.TARGET_ARRAY_BUFFER)
521 attributes[f"JOINTS_{k}"] = _accessor(accessors, jv, COMPONENT_UNSIGNED_SHORT, len(mesh["joints"]), "VEC4")
522 wv = _view(buf, views, _floats([x for row in mesh["weights"] for x in row[4 * k:4 * k + 4]]),
523 target=glb_writer.TARGET_ARRAY_BUFFER)
524 attributes[f"WEIGHTS_{k}"] = _accessor(accessors, wv, COMPONENT_FLOAT, len(mesh["weights"]), "VEC4")
525 gltf_meshes.append({"name": mesh["name"], "primitives": [{"attributes": attributes, "indices": index_accessor,
526 "mode": glb_writer.MODE_TRIANGLES}]})
527 scene_nodes.append(len(nodes))
528 # A skinned mesh's own transform is ignored (glTF 2.0, 3.7.3), so its node sits at the scene root.
529 nodes.append({"name": mesh["name"], "mesh": len(gltf_meshes) - 1, "skin": 0})
530 animations = []
531 for name, channels in clips:
532 samplers, out_channels = [], []
533 for (target, path), keys in sorted(channels.items(), key=lambda kv: (str(kv[0][0]), kv[0][1])):
534 times = [t for t, _v in keys]
535 require(all(b > a for a, b in zip(times, times[1:])), "key times are not increasing")
536 tv = _view(buf, views, _floats(times))
537 ta = _accessor(accessors, tv, COMPONENT_FLOAT, len(times), "SCALAR", min=[min(times)], max=[max(times)])
538 values = [x for _t, v in keys for x in v]
539 vv = _view(buf, views, _floats(values))
540 va = _accessor(accessors, vv, COMPONENT_FLOAT, len(keys), "VEC4" if path == "rotation" else "VEC3")
541 samplers.append({"input": ta, "output": va, "interpolation": "LINEAR"})
542 node = mover if target == "mover" else first_joint + target
543 out_channels.append({"sampler": len(samplers) - 1, "target": {"node": node, "path": path}})
544 if out_channels:
545 animations.append({"name": name, "samplers": samplers, "channels": out_channels})
546 gltf = {
547 "asset": {"version": "2.0", "generator": generator},
548 "scene": 0, "scenes": [{"nodes": scene_nodes}], "nodes": nodes, "skins": [skin], "meshes": gltf_meshes,
549 "accessors": accessors, "bufferViews": views, "buffers": [{"byteLength": len(buf)}],
550 }
551 if animations:
552 gltf["animations"] = animations
553 return pack_glb(gltf, buf), gltf
554
555
556def pack_glb(gltf, buf):
557 buf = bytes(buf) + b"\0" * ((-len(buf)) % 4)
558 gltf["buffers"][0]["byteLength"] = len(buf)
559 text = json.dumps(gltf, separators=(",", ":"), allow_nan=False).encode("utf-8")
560 text += b" " * ((-len(text)) % 4)
561 total = 12 + 8 + len(text) + 8 + len(buf)
562 return b"".join((struct.pack("<4sII", glb_writer.GLB_MAGIC, glb_writer.GLB_VERSION, total),
563 struct.pack("<II", len(text), glb_writer.CHUNK_TYPE_JSON), text,
564 struct.pack("<II", len(buf), glb_writer.CHUNK_TYPE_BIN), buf))
565
566
567# ---------------------------------------------------------------- commands
568
569
570def parse_offset(text):
571 value, _, child = text.partition(":")
572 try:
573 return int(value, 0), (int(child, 0) if child else None)
574 except ValueError:
575 raise argparse.ArgumentTypeError(f"not an offset: {text!r}") from None
576
577
578def same_path(first, second):
579 return anim_clips.same_output_path(first, second)
580
581
582def export(args):
583 started = time.monotonic()
584 report = {"archive": os.path.basename(args.archive), "parts": [], "clips": [], "counts": collections.Counter()}
585 with open(args.archive, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m:
586 sys_pages, _gfx = load_resource(m, args.skeleton[0])
587 joints, worst = read_skeleton(sys_pages, drawable_at(sys_pages, args.skeleton[1]))
588 require(worst < 1e-3, f"default transforms disagree with the inverse bind matrices by {worst:.4g}")
589 report["skeleton"] = {"offset": f"0x{args.skeleton[0]:x}", "joints": len(joints), "bind_error": worst}
590 meshes = []
591 for offset, child in args.part:
592 sys_pages, gfx = load_resource(m, offset)
593 drawable = drawable_at(sys_pages, child)
594 name = c_string(sys_pages, drawable + 168) or f"part_0x{offset:x}"
595 if name.endswith(".#dr"):
596 name = name[:-4]
597 part = bind_part(read_part(sys_pages, gfx, drawable, args.lod), joints, args.max_influences)
598 for mesh in part:
599 mesh["name"] = f"{name}_m{mesh['model']}_g{mesh['geometry']}"
600 meshes.extend(part)
601 report["parts"].append({"offset": f"0x{offset:x}", "child": child, "meshes": len(part),
602 "vertices": sum(len(x["positions"]) for x in part),
603 "triangles": sum(len(x["indices"]) // 3 for x in part),
604 "layouts": sorted({x["layout"] for x in part})})
605 require(meshes, "no part meshes")
606 clips = []
607 if args.anim:
608 s, dictionary = load_dictionary(args.anim, args.dictionary)
609 joint_by_hash = {}
610 for i, j in enumerate(joints):
611 joint_by_hash.setdefault(j["hash"], i)
612 for clip in select_clips(dictionary, args.clip):
613 tally = collections.Counter()
614 channels = clip_channels(s, dictionary, clip, joint_by_hash, not args.no_root_motion, tally)
615 clips.append((clip_label(clip), channels))
616 report["clips"].append(dict(hash=f"0x{clip['hash']:08x}", channels=len(channels), **tally))
617 data, gltf = build(joints, meshes, clips, root_motion=not args.no_root_motion)
618 glb_writer._write_bytes_atomic(args.out, data)
619 report["counts"].update(meshes=len(meshes), animations=len(gltf.get("animations", [])), bytes=len(data))
620 report["seconds"] = round(time.monotonic() - started, 2)
621 return report
622
623
624def coverage_worker(job):
625 """Count the bone tracks of the clip dictionaries in one slice of anim.rpf that name a skeleton joint."""
626 path, segments_list, hashes = job
627 counts = collections.Counter()
628 hashes = set(hashes)
629 for segments in segments_list:
630 with open(path, "rb") as fh:
631 data = b""
632 for off, stored, raw in segments:
633 fh.seek(off)
634 data += fh.read(stored) if raw else zlib.decompressobj().decompress(fh.read(stored))
635 try:
636 d = anim_clips.parse_dictionary(anim_clips.System(data))
637 except (anim_clips.DecodeError, struct.error):
638 counts["dictionaries_not_read"] += 1
639 continue
640 counts["dictionaries"] += 1
641 bones, hit = set(), set()
642 for pack in d["packs"]:
643 for anim in pack["animations"]:
644 for bone, ttype, _fmt in anim["tracks"]:
645 if ttype not in TRACK_PATHS or bone == 0:
646 continue
647 counts["bone_tracks"] += 1
648 bones.add(bone)
649 if bone in hashes:
650 counts["bone_tracks_in_skeleton"] += 1
651 hit.add(bone)
652 if bones:
653 counts["dictionaries_with_bone_tracks"] += 1
654 share = len(hit) / len(bones)
655 counts["dictionaries_all_bones_in_skeleton"] += share == 1
656 counts["dictionaries_90pct_bones_in_skeleton"] += share >= 0.9
657 counts["dictionaries_no_bone_in_skeleton"] += not hit
658 return counts
659
660
661def coverage(args):
662 started = time.monotonic()
663 with open(args.archive, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m:
664 sys_pages, _gfx = load_resource(m, args.skeleton[0])
665 joints, worst = read_skeleton(sys_pages, drawable_at(sys_pages, args.skeleton[1]))
666 rows, _walk = anim_index.scan_rpf(args.anim)
667 with open(args.anim, "rb") as fh, mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as m:
668 groups, _unresolved, _gaps = anim_clips.group(m, rows)
669 segments = [[anim_clips.segment(rows, k) for k in parts] for _root, parts in groups]
670 hashes = sorted({j["hash"] for j in joints})
671 jobs = max(1, args.jobs)
672 slices = [(args.anim, segments[i::jobs], hashes) for i in range(jobs)]
673 total = collections.Counter()
674 if jobs == 1:
675 total.update(coverage_worker(slices[0]))
676 else:
677 from concurrent.futures import ProcessPoolExecutor
678 with ProcessPoolExecutor(jobs) as ex:
679 for part in ex.map(coverage_worker, slices):
680 total.update(part)
681 return {"skeleton": {"offset": f"0x{args.skeleton[0]:x}", "joints": len(joints), "bind_error": worst},
682 "counts": dict(sorted(total.items())), "seconds": round(time.monotonic() - started, 1)}
683
684
685def main(argv=None):
686 ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
687 ap.add_argument("archive", help="archive holding the skeleton and the parts (packs.rpf)")
688 ap.add_argument("out", nargs="?", help="output .glb (export mode)")
689 ap.add_argument("--skeleton", type=parse_offset, required=True, help="resource with the skeleton, <offset>[:<child>]")
690 ap.add_argument("--part", type=parse_offset, action="append", default=[], help="part drawable, <offset>[:<child>]")
691 ap.add_argument("--anim", help="anim.rpf")
692 ap.add_argument("--dictionary", type=lambda t: parse_offset(t)[0], help="clip dictionary offset in --anim")
693 ap.add_argument("--clip", action="append", default=[], help="clip name (without pack:/ and .clip) or 0xhash")
694 ap.add_argument("--lod", type=int, default=0, help="LOD level of the parts (0 = highest)")
695 ap.add_argument("--max-influences", type=int, choices=(4, 8), default=8,
696 help="bone influences per vertex; 4 keeps the largest four, renormalised (three.js reads four)")
697 ap.add_argument("--no-root-motion", action="store_true", help="leave out the mover (bone hash 0) tracks")
698 ap.add_argument("--coverage", action="store_true", help="count clip bone tracks that name a skeleton joint")
699 ap.add_argument("--jobs", type=int, default=1, help="worker processes for --coverage")
700 ap.add_argument("--report", help="write a JSON report (counts only)")
701 args = ap.parse_args(argv)
702 inputs = [args.archive] + ([args.anim] if args.anim else [])
703 outputs = [p for p in (args.out, args.report) if p]
704 for o in outputs:
705 for i in inputs:
706 if os.path.exists(o) and same_path(i, o):
707 ap.error(f"{o} is an input; refusing to overwrite it")
708 if args.out and args.report and same_path(args.out, args.report):
709 ap.error("the GLB and the report are the same path")
710 if args.coverage:
711 if not args.anim or not args.report:
712 ap.error("--coverage needs --anim and --report")
713 if args.out:
714 ap.error("--coverage writes no GLB")
715 else:
716 if not args.out or not args.part:
717 ap.error("export needs <out.glb> and at least one --part")
718 if args.anim and args.dictionary is None:
719 ap.error("--anim needs --dictionary")
720 try:
721 report = coverage(args) if args.coverage else export(args)
722 except (ExportError, anim_clips.DecodeError, struct.error, OSError, ValueError) as e:
723 print(f"ERROR: {e}", file=sys.stderr)
724 return 2
725 if args.report:
726 with open(args.report, "w", encoding="utf-8", newline="\n") as f:
727 json.dump(report, f, indent=1, sort_keys=True)
728 f.write("\n")
729 print(json.dumps({k: v for k, v in report.items() if k in ("counts", "skeleton", "seconds")}, sort_keys=True))
730 return 0
731
732
733if __name__ == "__main__":
734 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
735 sys.stdout.reconfigure(errors="replace")
736 except (AttributeError, ValueError, OSError):
737 pass
738 sys.exit(main())
diff --git a/tools/anim_index.py b/tools/anim_index.py
index 119b81613..9663e6549 100644
--- a/tools/anim_index.py
+++ b/tools/anim_index.py
@@ -292,7 +292,7 @@ def collect_skeletons_dir(path):
292 out = [] 292 out = []
293 for name in sorted(os.listdir(path)): 293 for name in sorted(os.listdir(path)):
294 full = os.path.join(path, name) 294 full = os.path.join(path, name)
295 if not os.path.isfile(full) or os.path.getsize(full) > 16384: 295 if not os.path.isfile(full) or name.lower().endswith((".json", ".csv")) or os.path.getsize(full) > 16384:
296 continue 296 continue
297 with open(full, "rb") as f: 297 with open(full, "rb") as f:
298 data = f.read() 298 data = f.read()
@@ -308,9 +308,9 @@ def collect_skeletons_dir(path):
308def collect_rbf0_dir(path): 308def collect_rbf0_dir(path):
309 """The same continuation rule for a carved directory sorted by offset.""" 309 """The same continuation rule for a carved directory sorted by offset."""
310 entries = [] 310 entries = []
311 for name in os.listdir(path): 311 for name in sorted(os.listdir(path)):
312 full = os.path.join(path, name) 312 full = os.path.join(path, name)
313 if not os.path.isfile(full): 313 if not os.path.isfile(full) or name.lower().endswith((".json", ".csv")):
314 continue 314 continue
315 m = re.match(r"([0-9a-fA-F]{6,})", name) 315 m = re.match(r"([0-9a-fA-F]{6,})", name)
316 offset = int(m.group(1), 16) if m else len(entries) 316 offset = int(m.group(1), 16) if m else len(entries)
@@ -532,8 +532,40 @@ def main():
532 ap.add_argument("--rigs", metavar="PATH", help="write parsed RBF0 rig-set/rig and SKEL_ JSON here") 532 ap.add_argument("--rigs", metavar="PATH", help="write parsed RBF0 rig-set/rig and SKEL_ JSON here")
533 ap.add_argument("--quiet", action="store_true") 533 ap.add_argument("--quiet", action="store_true")
534 a = ap.parse_args() 534 a = ap.parse_args()
535 if a.rigs and same_report_path(a.out, a.rigs): 535 if same_report_path(a.source, a.out):
536 ap.error("index and --rigs must use different paths") 536 ap.error("output must not overwrite the source")
537 if a.rigs:
538 if same_report_path(a.source, a.rigs):
539 ap.error("--rigs must not overwrite the source")
540 if same_report_path(a.out, a.rigs):
541 ap.error("index and --rigs must use different paths")
542 if os.path.isdir(a.out):
543 ap.error(f"{a.out} is a folder, not a .csv or .json file")
544 if a.rigs and os.path.isdir(a.rigs):
545 ap.error(f"{a.rigs} is a folder, not a JSON file")
546 if os.path.isdir(a.source):
547 manifest = os.path.join(a.source, "index.json")
548 for flag, path in (("output", a.out), ("--rigs", a.rigs)):
549 if not path:
550 continue
551 if os.path.isfile(manifest) and same_report_path(manifest, path):
552 ap.error(f"{flag} would overwrite the carve manifest: {path}")
553 if os.path.isfile(path):
554 for name in os.listdir(a.source):
555 inp = os.path.join(a.source, name)
556 if os.path.isfile(inp) and not name.lower().endswith((".json", ".csv")):
557 if same_report_path(inp, path):
558 ap.error(f"{flag} would overwrite an input file: {path}")
559 if os.path.splitext(a.out)[1].lower() not in (".json", ".csv"):
560 ap.error("output must end in .json or .csv")
561 if a.rigs and os.path.splitext(a.rigs)[1].lower() != ".json":
562 ap.error("--rigs must end in .json")
563 for flag, path in (("output", a.out), ("--rigs", a.rigs)):
564 if not path:
565 continue
566 folder = os.path.dirname(os.path.abspath(path))
567 if not os.path.isdir(folder):
568 sys.exit(f"{path}: cannot write: folder does not exist: {folder}")
537 try: 569 try:
538 if os.path.isdir(a.source): 570 if os.path.isdir(a.source):
539 if a.start is not None or a.limit is not None: 571 if a.start is not None or a.limit is not None:
diff --git a/tools/anim_rigs.py b/tools/anim_rigs.py
index 085015131..7e7ef39eb 100644
--- a/tools/anim_rigs.py
+++ b/tools/anim_rigs.py
@@ -17,6 +17,10 @@ import struct
17import sys 17import sys
18import zlib 18import zlib
19 19
20# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module.
21sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
22from report_paths import same_report_path # noqa: E402
23
20sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) 24sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
21import anim_clips # noqa: E402 25import anim_clips # noqa: E402
22import anim_index # noqa: E402 26import anim_index # noqa: E402
@@ -115,7 +119,10 @@ def scan(path, start=None, limit=None):
115 119
116def join_rbf0(dicts, rigs): 120def join_rbf0(dicts, rigs):
117 """Resolve the rig-set manager's entries: source = rig dictionary name, joaat32(rig) = a key there.""" 121 """Resolve the rig-set manager's entries: source = rig dictionary name, joaat32(rig) = a key there."""
118 keys = {d["name"]: {e["key"] for e in d.get("entries", ())} for d in dicts if d.get("name")} 122 keys: collections.defaultdict[str, set[int]] = collections.defaultdict(set)
123 for dictionary in dicts:
124 if name := dictionary.get("name"):
125 keys[name].update(entry["key"] for entry in dictionary.get("entries", ()))
119 entries = [e for rs in rigs["rbf0"]["rigsets"] for e in rs["entries"]] 126 entries = [e for rs in rigs["rbf0"]["rigsets"] for e in rs["entries"]]
120 c = collections.Counter() 127 c = collections.Counter()
121 for e in entries: 128 for e in entries:
@@ -144,6 +151,12 @@ def main():
144 ap.add_argument("--start", type=anim_index.offset, help="first byte to scan (default: the RPF data start)") 151 ap.add_argument("--start", type=anim_index.offset, help="first byte to scan (default: the RPF data start)")
145 ap.add_argument("--limit", type=anim_index.byte_count, help="number of bytes to scan") 152 ap.add_argument("--limit", type=anim_index.byte_count, help="number of bytes to scan")
146 a = ap.parse_args() 153 a = ap.parse_args()
154 if os.path.isdir(a.out):
155 ap.error(f"{a.out} is a folder, not a file")
156 if same_report_path(a.out, a.archive):
157 ap.error(f"{a.out} would overwrite the input archive")
158 if a.rigs and same_report_path(a.out, a.rigs):
159 ap.error(f"{a.out} would overwrite the --rigs input")
147 try: 160 try:
148 dicts, summary = scan(a.archive, a.start, a.limit) 161 dicts, summary = scan(a.archive, a.start, a.limit)
149 if a.rigs: 162 if a.rigs:
@@ -155,10 +168,12 @@ def main():
155 sys.exit(f"{e.filename or a.archive}: {e.strerror or e}") 168 sys.exit(f"{e.filename or a.archive}: {e.strerror or e}")
156 rows = [{k: v for k, v in d.items() if k != "entries"} | {"entries": len(d.get("entries", ()))} for d in dicts] 169 rows = [{k: v for k, v in d.items() if k != "entries"} | {"entries": len(d.get("entries", ()))} for d in dicts]
157 try: 170 try:
171 os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
158 with open(a.out, "w", encoding="utf-8", newline="\n") as f: 172 with open(a.out, "w", encoding="utf-8", newline="\n") as f:
159 json.dump({"summary": summary, "rig_dictionaries": rows}, f, indent=1) 173 json.dump({"summary": summary, "rig_dictionaries": rows}, f, indent=1)
160 except OSError as e: 174 except OSError as e:
161 sys.exit(f"{a.out}: cannot write: {e.strerror or e}") 175 print(f"ERROR: cannot write {a.out}: {e.strerror or e}", file=sys.stderr)
176 return 2
162 c = summary["counts"] 177 c = summary["counts"]
163 print(json.dumps({k: c.get(k, 0) for k in ("rig_dictionaries", "entries", "entries_with_block", "tables")})) 178 print(json.dumps({k: c.get(k, 0) for k in ("rig_dictionaries", "entries", "entries_with_block", "tables")}))
164 if "rbf0_join" in summary: 179 if "rbf0_join" in summary:
diff --git a/tools/audio_wav.py b/tools/audio_wav.py
index 1d8e90ef3..cbeff22d5 100644
--- a/tools/audio_wav.py
+++ b/tools/audio_wav.py
@@ -31,6 +31,7 @@ import subprocess
31import sys 31import sys
32import tempfile 32import tempfile
33import time 33import time
34from typing import BinaryIO
34import unicodedata 35import unicodedata
35 36
36EXTS = (".ogg", ".opus") 37EXTS = (".ogg", ".opus")
@@ -61,11 +62,27 @@ def find_ffmpeg(explicit: str):
61 return found 62 return found
62 63
63 64
65def _read_opus_id(stream: BinaryIO) -> tuple[bytes, bytes] | None:
66 """Read the Opus ID packet and serial, leaving the stream at the next page."""
67 header = stream.read(27)
68 if len(header) != 27 or header[:6] != b"OggS\x00\x02":
69 return None
70 lacing = stream.read(header[26])
71 # An Opus identification packet completes on the BOS page and is its only packet (RFC 7845).
72 if len(lacing) != header[26] or not lacing or lacing[-1] == 255 or any(v != 255 for v in lacing[:-1]):
73 return None
74 size = sum(lacing)
75 packet = stream.read(size)
76 if len(packet) != size or size < 19 or not packet.startswith(b"OpusHead"):
77 return None
78 return packet, header[14:18]
79
80
64def looks_like_opus(path: str) -> bool: 81def looks_like_opus(path: str) -> bool:
65 """True if the first Ogg page carries an OpusHead packet (so .ogg files that are Vorbis are left alone).""" 82 """True if the first Ogg page carries an OpusHead packet (so .ogg files that are Vorbis are left alone)."""
66 try: 83 try:
67 with open(path, "rb") as f: 84 with open(path, "rb") as f:
68 return b"OpusHead" in f.read(512) 85 return _read_opus_id(f) is not None
69 except OSError: 86 except OSError:
70 return True # let ffmpeg report the real problem 87 return True # let ffmpeg report the real problem
71 88
@@ -75,23 +92,15 @@ def ogg_output_samples(path: str) -> int:
75 try: 92 try:
76 size = os.path.getsize(path) 93 size = os.path.getsize(path)
77 with open(path, "rb") as f: 94 with open(path, "rb") as f:
78 first = f.read(65536) 95 identification = _read_opus_id(f)
79 if len(first) < 27 or first[:6] != b"OggS\x00\x02": 96 if identification is None:
80 return 0
81 # The Opus ID packet must finish on the BOS page and be its only packet.
82 body_start = 27 + first[26]
83 lacing = first[27:body_start]
84 if not lacing or lacing[-1] == 255 or lacing[:-1].count(255) != len(lacing) - 1:
85 return 0 97 return 0
86 body_end = body_start + sum(lacing) 98 head, serial = identification
87 head = first[body_start:body_end] 99 if head[8] >= 16 or head[9] == 0:
88 if (body_end > len(first) or len(head) < 19 or not head.startswith(b"OpusHead")
89 or head[8] >= 16 or head[9] == 0):
90 return 0 100 return 0
91 serial = first[14:18]
92 pre_skip, = struct.unpack_from("<H", head, 10) 101 pre_skip, = struct.unpack_from("<H", head, 10)
93 # Walk page headers forward so same-serial chained or multiplexed streams are rejected. 102 # Walk page headers forward so same-serial chained or multiplexed streams are rejected.
94 offset = body_end 103 offset = f.tell()
95 while offset < size: 104 while offset < size:
96 f.seek(offset) 105 f.seek(offset)
97 hdr = f.read(27) 106 hdr = f.read(27)
@@ -472,14 +481,16 @@ def main(argv=None) -> int:
472 t0 = time.time() 481 t0 = time.time()
473 written = skipped = 0 482 written = skipped = 0
474 todo = [] 483 todo = []
484 failures: list[tuple[str, str]] = []
475 for path, rel in items: 485 for path, rel in items:
476 dst = os.path.join(out, rel + ".wav") 486 dst = os.path.join(out, rel + ".wav")
477 if os.path.exists(dst): 487 if os.path.isfile(dst):
478 skipped += 1 488 skipped += 1
489 elif os.path.exists(dst):
490 failures.append((rel, f"output path is not a file: {dst}"))
479 else: 491 else:
480 todo.append((path, rel, dst)) 492 todo.append((path, rel, dst))
481 493
482 failures = []
483 done = 0 494 done = 0
484 workers = min(a.jobs, len(todo)) if todo else 1 495 workers = min(a.jobs, len(todo)) if todo else 1
485 if todo: 496 if todo:
diff --git a/tools/awc_manifest.py b/tools/awc_manifest.py
index 79a8a5375..23c4cc3e3 100644
--- a/tools/awc_manifest.py
+++ b/tools/awc_manifest.py
@@ -33,6 +33,7 @@ import tempfile
33sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) 33sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
34import awc_opus # noqa: E402 34import awc_opus # noqa: E402
35from file_mode import published_mode # noqa: E402 35from file_mode import published_mode # noqa: E402
36from report_paths import same_report_path # noqa: E402
36 37
37FIELDS = ("bank", "stream", "codec", "codec_name", "channels", "sample_rate", "declared_samples", 38FIELDS = ("bank", "stream", "codec", "codec_name", "channels", "sample_rate", "declared_samples",
38 "duration_s", "streamed_music", "data_offset", "data_size", "bank_size", "notes") 39 "duration_s", "streamed_music", "data_offset", "data_size", "bank_size", "notes")
@@ -145,15 +146,6 @@ def _bank_rows(path: str, bank: str) -> list:
145 return rows 146 return rows
146 147
147 148
148def _same_report_path(first: str, second: str) -> bool:
149 if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)):
150 return True
151 try:
152 return os.path.samefile(first, second)
153 except OSError:
154 return False
155
156
157def collect(src: str, *, out: str | None = None): 149def collect(src: str, *, out: str | None = None):
158 """(parsed bank count, rows, streamed-music row count); one warning per skipped bank. 150 """(parsed bank count, rows, streamed-music row count); one warning per skipped bank.
159 151
@@ -172,7 +164,7 @@ def collect(src: str, *, out: str | None = None):
172 banks = [src] 164 banks = [src]
173 if out: 165 if out:
174 for path in banks: 166 for path in banks:
175 if _same_report_path(out, path): 167 if same_report_path(out, path):
176 raise ValueError(f"--out would overwrite the input {path}") 168 raise ValueError(f"--out would overwrite the input {path}")
177 rows = [] 169 rows = []
178 parsed = 0 170 parsed = 0
diff --git a/tools/awc_names.py b/tools/awc_names.py
index ec3568e34..5af62e5a5 100644
--- a/tools/awc_names.py
+++ b/tools/awc_names.py
@@ -22,7 +22,8 @@ Dictionary sources:
22 ``<key>_<N>``: wave ``_01`` speaks the first label, ``_02`` the second, and so on. 22 ``<key>_<N>``: wave ``_01`` speaks the first label, ``_02`` the second, and so on.
23 23
24Bank sources (positional; each one is reported and thresholded on its own): ``.awc`` files, directories searched 24Bank sources (positional; each one is reported and thresholded on its own): ``.awc`` files, directories searched
25for ``.awc`` files, or an ``audio_manifest.json`` written by ``rpf9dump audio``. 25for ``.awc`` files, or an ``audio_manifest.json`` written by ``rpf9dump audio``. Sources with the same basename
26include their parent paths in report labels so they can be selected separately with ``opus_tags.py --source``.
26 27
27Usage: 28Usage:
28 python -I awc_names.py <banks> [<banks> ...] (--words FILE | --conversations PATH) [...] 29 python -I awc_names.py <banks> [<banks> ...] (--words FILE | --conversations PATH) [...]
@@ -265,8 +266,23 @@ def name_source(dictionary: Dictionary, bases: list, index: Index) -> tuple:
265 return real, stats 266 return real, stats
266 267
267 268
268def _label(source: str) -> str: 269def source_labels(sources):
269 return os.path.basename(os.path.normpath(source)) or source 270 """Keep basename labels where possible and qualify collisions relative to their shared parent."""
271 labels = {src: os.path.basename(os.path.normpath(src)) or src for src in sources}
272 groups = collections.defaultdict(list)
273 for src, label in labels.items():
274 groups[label].append(src)
275 for group in groups.values():
276 if len(group) < 2:
277 continue
278 paths = [os.path.abspath(src) for src in group]
279 try:
280 parent = os.path.commonpath([os.path.dirname(path) for path in paths])
281 except ValueError: # Different Windows drives have no shared parent.
282 parent = None
283 for src, path in zip(group, paths):
284 labels[src] = (os.path.relpath(path, parent) if parent else path).replace(os.sep, "/")
285 return labels
270 286
271 287
272def main(argv=None) -> int: 288def main(argv=None) -> int:
@@ -299,6 +315,7 @@ def main(argv=None) -> int:
299 f"{len(bases)} family bases", flush=True) 315 f"{len(bases)} family bases", flush=True)
300 316
301 rows, summary = [], {} 317 rows, summary = [], {}
318 labels = source_labels(a.banks)
302 for source in a.banks: 319 for source in a.banks:
303 try: 320 try:
304 banks = load_banks(source) 321 banks = load_banks(source)
@@ -307,7 +324,7 @@ def main(argv=None) -> int:
307 return 2 324 return 2
308 index = Index(banks) 325 index = Index(banks)
309 found, stats = name_source(dictionary, bases, index) 326 found, stats = name_source(dictionary, bases, index)
310 label = _label(source) 327 label = labels[source]
311 summary[label] = stats 328 summary[label] = stats
312 for (b, i), (name, rule, _k) in sorted(found.items()): 329 for (b, i), (name, rule, _k) in sorted(found.items()):
313 rows.append({"source": label, "bank": index.labels[b], "stream_id": f"{i:08x}", "name": name, 330 rows.append({"source": label, "bank": index.labels[b], "stream_id": f"{i:08x}", "name": name,
diff --git a/tools/awc_opus.py b/tools/awc_opus.py
index 5bad0dfbb..bb03120d2 100644
--- a/tools/awc_opus.py
+++ b/tools/awc_opus.py
@@ -164,9 +164,14 @@ def write_file(path: str, data: bytes) -> None:
164 164
165def write_wav(path: str, pcm: bytes, rate: int, channels: int, float32: bool = False) -> None: 165def write_wav(path: str, pcm: bytes, rate: int, channels: int, float32: bool = False) -> None:
166 bits = 32 if float32 else 16 166 bits = 32 if float32 else 16
167 hdr = b"RIFF" + struct.pack("<I", 36 + len(pcm)) + b"WAVEfmt " + struct.pack( 167 block_align = channels * (bits // 8)
168 "<IHHIIHH", 16, 3 if float32 else 1, channels, rate, rate * channels * bits // 8, channels * bits // 8, bits) + b"data" + struct.pack("<I", len(pcm)) 168 fmt = struct.pack("<HHIIHH", 3 if float32 else 1, channels, rate, rate * block_align, block_align, bits)
169 write_file(path, hdr + pcm) 169 fact = b""
170 if float32:
171 fmt += struct.pack("<H", 0) # WAVEFORMATEX.cbSize
172 fact = struct.pack("<4sII", b"fact", 4, len(pcm) // block_align)
173 header = b"WAVEfmt " + struct.pack("<I", len(fmt)) + fmt + fact + b"data" + struct.pack("<I", len(pcm))
174 write_file(path, b"RIFF" + struct.pack("<I", len(header) + len(pcm)) + header + pcm)
170 175
171 176
172# ---- AWC ---- 177# ---- AWC ----
diff --git a/tools/batch_glb.py b/tools/batch_glb.py
new file mode 100644
index 000000000..e62b6fe42
--- /dev/null
+++ b/tools/batch_glb.py
@@ -0,0 +1,208 @@
1"""Batch converter from Wavefront OBJ files to binary glTF 2.0 (.glb).
2
3Uses tools/glb_writer.py to process entire directories of OBJ models
4with multi-core parallelism and progress reporting. Can optionally link
5and embed textures (.png or .dds) directly into glTF materials.
6
7Usage:
8 python -I tools/batch_glb.py <in_dir> <out_dir> [--jobs N] [--up z|y] [--textures <dir>]
9"""
10from __future__ import annotations
11
12import argparse
13import concurrent.futures
14import os
15import sys
16import time
17
18sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
19import glb_writer
20import dds_png
21
22
23def _build_texture_index(texture_dir: str | None) -> dict[str, str]:
24 """Index available texture files (.png and .dds) by lowercase basename without extension."""
25 if not texture_dir or not os.path.isdir(texture_dir):
26 return {}
27 index: dict[str, str] = {}
28 for entry in os.scandir(texture_dir):
29 if not entry.is_file():
30 continue
31 lower = entry.name.lower()
32 if lower.endswith(".png") or lower.endswith(".dds"):
33 stem = os.path.splitext(lower)[0]
34 # Prefer png over dds if both exist
35 if stem not in index or lower.endswith(".png"):
36 index[stem] = entry.path
37 return index
38
39
40def _load_png_bytes(tex_path: str, max_size: int = 0) -> bytes | None:
41 """Load PNG bytes from file or decode DDS directly to PNG bytes."""
42 lower = tex_path.lower()
43 if lower.endswith(".png"):
44 with open(tex_path, "rb") as f:
45 return f.read()
46 elif lower.endswith(".dds"):
47 try:
48 return dds_png.dds_file_to_png_bytes(tex_path, max_size=max_size)
49 except Exception:
50 return None
51 return None
52
53
54def convert_single(
55 args_tuple: tuple[str, str, str, dict[str, str], int, dict[str, bytes]],
56) -> tuple[bool, str, str]:
57 in_path, out_path, up_axis, tex_index, max_tex_size, tex_cache = args_tuple
58 try:
59 primitives = glb_writer.parse_obj(in_path, is_path=True, up_axis=up_axis)
60 materials: dict[str, dict] = {}
61
62 if tex_index:
63 base_stem = os.path.splitext(os.path.basename(in_path))[0].lower()
64 # Clean possible hash suffix like 'ambient_femalebb._ft_at_...' -> 'ambient_femalebb'
65 clean_stem = base_stem.split(".")[0]
66
67 for prim in primitives:
68 mat_name = prim.get("material", "")
69 lookup_keys = []
70 if mat_name:
71 lookup_keys.extend([
72 mat_name.lower(),
73 f"{mat_name.lower()}_d",
74 f"{mat_name.lower()}_diff",
75 ])
76 lookup_keys.extend([
77 base_stem,
78 clean_stem,
79 f"{clean_stem}_d",
80 f"{clean_stem}_diff",
81 ])
82
83 found_path = None
84 for key in lookup_keys:
85 if key in tex_index:
86 found_path = tex_index[key]
87 break
88
89 if found_path:
90 png_bytes = tex_cache.get(found_path)
91 if png_bytes is None:
92 png_bytes = _load_png_bytes(found_path, max_size=max_tex_size)
93 if png_bytes:
94 tex_cache[found_path] = png_bytes
95 if png_bytes:
96 mat_key = mat_name if mat_name else clean_stem
97 prim["material"] = mat_key
98 materials[mat_key] = {
99 "name": mat_key,
100 "png_bytes": png_bytes,
101 }
102
103 glb_writer.write_glb(out_path, primitives, materials=materials if materials else None)
104 return True, in_path, ""
105 except Exception as exc:
106 return False, in_path, str(exc)
107
108
109def batch_convert(
110 in_dir: str,
111 out_dir: str,
112 up_axis: str = "z",
113 jobs: int | None = None,
114 texture_dir: str | None = None,
115 max_tex_size: int = 0,
116) -> dict[str, int]:
117 if not os.path.isdir(in_dir):
118 raise ValueError(f"Input directory does not exist: {in_dir}")
119
120 os.makedirs(out_dir, exist_ok=True)
121 obj_files = [
122 f for f in os.listdir(in_dir) if f.lower().endswith(".obj") and os.path.isfile(os.path.join(in_dir, f))
123 ]
124
125 tex_index = _build_texture_index(texture_dir)
126 tex_cache: dict[str, bytes] = {}
127
128 tasks = [
129 (
130 os.path.join(in_dir, f),
131 os.path.join(out_dir, os.path.splitext(f)[0] + ".glb"),
132 up_axis,
133 tex_index,
134 max_tex_size,
135 tex_cache,
136 )
137 for f in obj_files
138 ]
139
140 total = len(tasks)
141 succeeded = 0
142 failed = 0
143
144 max_workers = jobs if jobs and jobs > 0 else (os.cpu_count() or 4)
145
146 with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
147 for ok, path, err in executor.map(convert_single, tasks):
148 if ok:
149 succeeded += 1
150 else:
151 failed += 1
152
153 return {"total": total, "succeeded": succeeded, "failed": failed}
154
155
156def main(argv: list[str] | None = None) -> int:
157 parser = argparse.ArgumentParser(
158 description="Batch convert Wavefront OBJ models to binary glTF 2.0 (.glb)."
159 )
160 parser.add_argument("in_dir", help="Directory containing .obj files")
161 parser.add_argument("out_dir", help="Output directory for .glb files")
162 parser.add_argument(
163 "--jobs",
164 type=int,
165 default=None,
166 help="Number of parallel worker threads (default: CPU count)",
167 )
168 parser.add_argument(
169 "--up",
170 choices=("z", "y"),
171 default="z",
172 help="Source up axis: 'z' converts RAGE Z-up to glTF Y-up (default), 'y' keeps Y-up",
173 )
174 parser.add_argument(
175 "--textures",
176 type=str,
177 default=None,
178 help="Optional directory containing textures (.png or .dds) to link and embed",
179 )
180 parser.add_argument(
181 "--max-tex-size",
182 type=int,
183 default=0,
184 help="Max texture dimension in pixels when decoding DDS (0 = unconstrained)",
185 )
186
187 args = parser.parse_args(argv)
188 t0 = time.monotonic()
189 stats = batch_convert(
190 args.in_dir,
191 args.out_dir,
192 up_axis=args.up,
193 jobs=args.jobs,
194 texture_dir=args.textures,
195 max_tex_size=args.max_tex_size,
196 )
197 elapsed = time.monotonic() - t0
198
199 print(
200 f"batch_glb: converted {stats['succeeded']}/{stats['total']} models "
201 f"({stats['failed']} failed) in {elapsed:.2f}s"
202 )
203 return 0 if stats["failed"] == 0 else 1
204
205
206if __name__ == "__main__":
207 sys.stdout.reconfigure(errors="replace")
208 sys.exit(main())
diff --git a/tools/bcpack_tool.py b/tools/bcpack_tool.py
new file mode 100644
index 000000000..101190189
--- /dev/null
+++ b/tools/bcpack_tool.py
@@ -0,0 +1,243 @@
1"""DirectStorage BCPack bitstream inspection, decoding and profiling tool.
2
3Provides CLI inspection, diagnostics, statistical frequency profiling and
4decompression for Xbox Series BCPack streams (codecs BC1, BC3, BC4, BC5, BC6H, BC7).
5
6Usage:
7 python -I tools/bcpack_tool.py inspect <in.bin> --codec <1..7> --size <uncompressed_bytes> [--json]
8 python -I tools/bcpack_tool.py decode <in.bin> <out.bin> --codec <1..7> --size <uncompressed_bytes> [--provisional]
9 python -I tools/bcpack_tool.py profile <in.bin> --codec <1..7> --size <uncompressed_bytes>
10"""
11from __future__ import annotations
12
13import argparse
14import json
15import os
16import sys
17
18sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
19import bcpack
20
21
22def inspect_stream(raw: bytes, codec: int, out_size: int) -> dict:
23 """Analyze stream structure, compression ratio and per-lane statistics."""
24 if codec not in bcpack.ALL_CODECS:
25 raise ValueError(f"unsupported BCPack codec id: {codec}")
26
27 block_size = bcpack.BLOCK_BYTES[codec]
28 if out_size <= 0 or out_size % block_size != 0:
29 raise ValueError(
30 f"output size {out_size} is not a valid multiple of {bcpack.CODEC_NAMES[codec]} block size ({block_size})"
31 )
32
33 nblocks = out_size // block_size
34 lanes, used = bcpack.decode_lanes(raw, codec, out_size)
35
36 lane_widths = bcpack.LANE_WIDTHS[codec]
37 lane_reports = []
38 total_symbols = 0
39
40 for idx, lane in enumerate(lanes):
41 count = len(lane)
42 total_symbols += count
43 w = lane_widths[idx]
44 zeros = lane.count(0)
45 min_val = min(lane) if count else 0
46 max_val = max(lane) if count else 0
47 avg_val = (sum(lane) / count) if count else 0.0
48
49 lane_reports.append({
50 "lane": idx,
51 "bit_width": w,
52 "symbols": count,
53 "zeros": zeros,
54 "zero_percent": round(100.0 * zeros / count, 2) if count else 0.0,
55 "min": min_val,
56 "max": max_val,
57 "avg": round(avg_val, 2),
58 })
59
60 trailing_bytes = len(raw) - used
61 ratio = round(len(raw) / out_size, 4) if out_size else 0.0
62
63 return {
64 "codec": bcpack.CODEC_NAMES[codec],
65 "codec_id": codec,
66 "compressed_bytes": len(raw),
67 "bytes_used": used,
68 "trailing_zeros": trailing_bytes,
69 "uncompressed_bytes": out_size,
70 "blocks": nblocks,
71 "compression_ratio": ratio,
72 "total_symbols": total_symbols,
73 "lanes": lane_reports,
74 }
75
76
77def profile_stream(raw: bytes, codec: int, out_size: int) -> dict:
78 """Generate symbol frequency distribution profile across all lanes."""
79 info = inspect_stream(raw, codec, out_size)
80 lanes, _ = bcpack.decode_lanes(raw, codec, out_size)
81
82 histograms = []
83 for idx, lane in enumerate(lanes):
84 counts: dict[int, int] = {}
85 for sym in lane:
86 counts[sym] = counts.get(sym, 0) + 1
87 sorted_top = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:8]
88 histograms.append({
89 "lane": idx,
90 "unique_symbols": len(counts),
91 "top_symbols": [{"sym": s, "count": c} for s, c in sorted_top],
92 })
93
94 info["histograms"] = histograms
95 return info
96
97
98def decode_file(
99 in_path: str,
100 out_path: str,
101 codec: int,
102 out_size: int,
103 allow_provisional: bool = False,
104 history: str | None = None,
105) -> int:
106 """Decode compressed file and write decompressed blocks to disk."""
107 with open(in_path, "rb") as f:
108 raw = f.read()
109
110 data, prov = bcpack.decode_with_info(
111 raw, codec, out_size, allow_provisional=allow_provisional, history=history
112 )
113
114 parent = os.path.dirname(os.path.abspath(out_path))
115 if parent:
116 os.makedirs(parent, exist_ok=True)
117
118 with open(out_path, "wb") as f:
119 f.write(data)
120
121 return len(data)
122
123
124def main(argv: list[str] | None = None) -> int:
125 parser = argparse.ArgumentParser(
126 description="DirectStorage BCPack bitstream inspection, decoding and profiling tool."
127 )
128 sub = parser.add_subparsers(dest="command", required=True)
129
130 # inspect
131 p_insp = sub.add_parser("inspect", help="Inspect BCPack stream structure and lane statistics")
132 p_insp.add_argument("file", help="Path to raw BCPack compressed file")
133 p_insp.add_argument(
134 "--codec",
135 type=int,
136 required=True,
137 choices=sorted(bcpack.ALL_CODECS),
138 help="BCPack codec ID (1=BC1, 3=BC3, 4=BC4, 5=BC5, 6=BC6H, 7=BC7)",
139 )
140 p_insp.add_argument(
141 "--size",
142 type=int,
143 required=True,
144 help="Expected uncompressed size in bytes",
145 )
146 p_insp.add_argument(
147 "--json",
148 action="store_true",
149 help="Print machine-readable JSON output",
150 )
151
152 # profile
153 p_prof = sub.add_parser("profile", help="Generate detailed symbol frequency distribution")
154 p_prof.add_argument("file", help="Path to raw BCPack compressed file")
155 p_prof.add_argument(
156 "--codec",
157 type=int,
158 required=True,
159 choices=sorted(bcpack.ALL_CODECS),
160 help="BCPack codec ID",
161 )
162 p_prof.add_argument(
163 "--size",
164 type=int,
165 required=True,
166 help="Expected uncompressed size in bytes",
167 )
168
169 # decode
170 p_dec = sub.add_parser("decode", help="Decompress BCPack file to raw BCn blocks")
171 p_dec.add_argument("in_file", help="Path to input BCPack compressed file")
172 p_dec.add_argument("out_file", help="Path to output decompressed file")
173 p_dec.add_argument(
174 "--codec",
175 type=int,
176 required=True,
177 choices=sorted(bcpack.ALL_CODECS),
178 help="BCPack codec ID",
179 )
180 p_dec.add_argument(
181 "--size",
182 type=int,
183 required=True,
184 help="Expected uncompressed size in bytes",
185 )
186 p_dec.add_argument(
187 "--provisional",
188 action="store_true",
189 help="Allow provisional history and signatures",
190 )
191 p_dec.add_argument(
192 "--history",
193 type=str,
194 default=None,
195 help="Path to optional BC6H/BC7 history JSON or directory",
196 )
197
198 args = parser.parse_args(argv)
199
200 if args.command == "inspect":
201 with open(args.file, "rb") as f:
202 raw = f.read()
203 info = inspect_stream(raw, args.codec, args.size)
204 if args.json:
205 print(json.dumps(info, indent=2))
206 else:
207 print(
208 f"BCPack {info['codec']} stream: {info['compressed_bytes']} bytes -> "
209 f"{info['uncompressed_bytes']} bytes ({info['blocks']} blocks, ratio {info['compression_ratio']:.3f})"
210 )
211 print(f"Lanes ({len(info['lanes'])} active):")
212 for l in info['lanes']:
213 print(
214 f" lane {l['lane']:2d} (w={l['bit_width']:2d}b): {l['symbols']} syms, "
215 f"{l['zeros']} zeros ({l['zero_percent']}%), min {l['min']}, max {l['max']}, avg {l['avg']}"
216 )
217 return 0
218
219 elif args.command == "profile":
220 with open(args.file, "rb") as f:
221 raw = f.read()
222 prof = profile_stream(raw, args.codec, args.size)
223 print(json.dumps(prof, indent=2))
224 return 0
225
226 elif args.command == "decode":
227 written = decode_file(
228 args.in_file,
229 args.out_file,
230 args.codec,
231 args.size,
232 allow_provisional=args.provisional,
233 history=args.history,
234 )
235 print(f"Successfully decoded {written} bytes to {args.out_file}")
236 return 0
237
238 return 1
239
240
241if __name__ == "__main__":
242 sys.stdout.reconfigure(errors="replace")
243 sys.exit(main())
diff --git a/tools/bink_names.py b/tools/bink_names.py
index a31c3d2c6..1e6ebb1cc 100644
--- a/tools/bink_names.py
+++ b/tools/bink_names.py
@@ -131,7 +131,7 @@ def _int(value):
131 return int(value, 0) if isinstance(value, str) else int(value) 131 return int(value, 0) if isinstance(value, str) else int(value)
132 132
133 133
134def load_streams(source): 134def load_streams(source, skip_report=None):
135 """Stream rows (source, offset, size, width, height, frames) in archive order.""" 135 """Stream rows (source, offset, size, width, height, frames) in archive order."""
136 lower = source.lower() 136 lower = source.lower()
137 if os.path.isfile(source) and lower.endswith(".json"): 137 if os.path.isfile(source) and lower.endswith(".json"):
@@ -151,11 +151,13 @@ def load_streams(source):
151 rows = list(reader) 151 rows = list(reader)
152 label, start = "row {i}", 2 152 label, start = "row {i}", 2
153 else: 153 else:
154 rows, _summary = bink_index.scan_target(source) 154 rows, _summary = bink_index.scan_target(source, skip_report=skip_report)
155 label, start = "stream {i}", 1 155 label, start = "stream {i}", 1
156 out = [] 156 out = []
157 for j, row in enumerate(rows): 157 for j, row in enumerate(rows):
158 try: 158 try:
159 if not isinstance(row, dict):
160 raise TypeError("row is not an object")
159 out.append({"source": row["source"], "offset": _int(row["offset"]), "size": _int(row["size"]), 161 out.append({"source": row["source"], "offset": _int(row["offset"]), "size": _int(row["size"]),
160 "width": _int(row["width"]), "height": _int(row["height"]), "frames": _int(row["frames"])}) 162 "width": _int(row["width"]), "height": _int(row["height"]), "frames": _int(row["frames"])})
161 except (KeyError, ValueError, TypeError, OverflowError) as error: 163 except (KeyError, ValueError, TypeError, OverflowError) as error:
@@ -173,9 +175,20 @@ def load_pins(path):
173 if not path: 175 if not path:
174 return pins 176 return pins
175 with open(path, encoding="utf-8", newline="") as fh: 177 with open(path, encoding="utf-8", newline="") as fh:
176 for row in csv.DictReader(fh): 178 reader = csv.DictReader(fh)
177 key = (row.get("source") or "", _int(row["offset"])) 179 header = reader.fieldnames or []
178 pins.setdefault(key, set()).update(p.strip().lower() for p in row["path"].split("|") if p.strip()) 180 missing = [f for f in ("offset", "path") if f not in header]
181 if missing:
182 raise ValueError(f"CSV header is missing required fields: {', '.join(missing)}")
183 for j, row in enumerate(reader, start=2):
184 try:
185 key = ((row.get("source") or "").strip(), _int(row["offset"]))
186 raw_path = row["path"]
187 if not isinstance(raw_path, str):
188 raise TypeError("path is missing")
189 except (KeyError, ValueError, TypeError, OverflowError) as error:
190 raise ValueError(f"row {j} is missing or unusable: {error}") from None
191 pins.setdefault(key, set()).update(p.strip().lower() for p in raw_path.split("|") if p.strip())
179 return pins 192 return pins
180 193
181 194
@@ -327,15 +340,38 @@ def main(argv=None):
327 return 2 340 return 2
328 if a.out and any(bink_index.same_output_path(p, a.out) for p in inputs): 341 if a.out and any(bink_index.same_output_path(p, a.out) for p in inputs):
329 ap.error("--out must not overwrite an input") 342 ap.error("--out must not overwrite an input")
343 if a.out and os.path.isdir(a.out):
344 ap.error(f"--out is a folder, not a report file: {a.out}")
345 if a.out:
346 for folder in [p for p in [a.source, *a.mount] if os.path.isdir(p)]:
347 manifest = os.path.join(folder, "index.json")
348 if os.path.isfile(manifest) and bink_index.same_output_path(a.out, manifest):
349 ap.error(f"--out would overwrite the carve manifest: {a.out}")
350 if os.path.isfile(a.out):
351 for root, _dirs, names in os.walk(folder):
352 for name in names:
353 if name.lower().endswith((".json", ".csv")):
354 continue
355 if bink_index.same_output_path(os.path.join(root, name), a.out):
356 ap.error(f"--out would overwrite an input file: {a.out}")
330 357
331 names = read_mount_lists(a.mount)
332 try: 358 try:
333 streams = load_streams(a.source) 359 names = read_mount_lists(a.mount)
360 except (OSError, ValueError) as error:
361 print(f"bink_names: error: {error}", file=sys.stderr)
362 return 1
363 try:
364 streams = load_streams(a.source, skip_report=a.out if a.out and os.path.isfile(a.out) else None)
334 except (OSError, csv.Error, ValueError) as error: 365 except (OSError, csv.Error, ValueError) as error:
335 print(f"bink_names: error: {a.source}: {error}", file=sys.stderr) 366 print(f"bink_names: error: {a.source}: {error}", file=sys.stderr)
336 return 1 367 return 1
337 try: 368 try:
338 rows, unmatched = name_streams(names, streams, load_pins(a.pins), a.max_skip) 369 pins = load_pins(a.pins)
370 except (OSError, csv.Error, ValueError) as error:
371 print(f"bink_names: error: {a.pins}: {error}", file=sys.stderr)
372 return 1
373 try:
374 rows, unmatched = name_streams(names, streams, pins, a.max_skip)
339 except ValueError as error: 375 except ValueError as error:
340 print(f"bink_names: error: {error}", file=sys.stderr) 376 print(f"bink_names: error: {error}", file=sys.stderr)
341 return 1 377 return 1
diff --git a/tools/buffer_store_probe.py b/tools/buffer_store_probe.py
new file mode 100644
index 000000000..2d27b5da6
--- /dev/null
+++ b/tools/buffer_store_probe.py
@@ -0,0 +1,336 @@
1r"""Measure RDNA2 (GFX10) typed buffer store rounding and 2-component DST_SEL swizzling natively (SHADER-364).
2
3Two questions left open by #2022 (measured on RDNA3.5 gfx1150, needing RDNA2 gfx103x data):
41. UNORM/SNORM store rounding: does hardware round the exact product clamp(x) * scale once (0.3 * 65535 -> 19661)
5 with ties away from zero, or double-round through an intermediate f32 multiply (0.3 * 65535 -> 19660)?
62. 2-component buffer_store_format_xyzw channel mapping: why did gfx1150 write (x, w) instead of (x, y)?
7 This probe sweeps all 12 2-component formats in FORMATS with XY01 (runtime RG) and XYZW, plus all 216 valid
8 (DST_SEL_X, DST_SEL_Y, DST_SEL_Z) triples on 32_32_UINT, for both MUBUF (buffer_store_format_*) and MTBUF
9 (tbuffer_store_format_*), in wave32 and wave64.
10
11Usage:
12 python -I tools/buffer_store_probe.py [--waves 32,64] [--json out.json]
13 python -I tools/buffer_store_probe.py --self-test # pure-Python model checks, no GPU
14
15Exit 0 when the sweep ran and matched the model (or --self-test passed), 1 on a wave32/wave64 or model mismatch,
162 on a harness error, 77 when tools/hw_oracle is unavailable or the GPU is not GFX10. Standard library only;
17nothing here reads game files.
18"""
19import argparse
20import itertools
21import json
22import os
23import struct
24import sys
25from fractions import Fraction
26
27HERE = os.path.dirname(os.path.abspath(__file__))
28sys.dont_write_bytecode = True
29if HERE not in sys.path:
30 sys.path.insert(0, HERE)
31
32# (name, GFX10 format code, kind, x channel bits)
33NORM_FORMATS = (
34 ("unorm16", 7, "unorm", 16),
35 ("snorm16", 8, "snorm", 16),
36 ("unorm8", 1, "unorm", 8),
37 ("snorm8", 2, "snorm", 8),
38 ("unorm10", 50, "unorm", 10),
39)
40
41# All 12 2-component formats in Gen.FORMATS: (name, code, kind, element_mask_or_None_for_64bit)
42TWO_COMP_FORMATS = (
43 ("8_8_UNORM", 14, "unorm", 0xFFFF),
44 ("8_8_SNORM", 15, "snorm", 0xFFFF),
45 ("8_8_UINT", 18, "uint", 0xFFFF),
46 ("8_8_SINT", 19, "sint", 0xFFFF),
47 ("16_16_UNORM", 23, "unorm", 0xFFFFFFFF),
48 ("16_16_SNORM", 24, "snorm", 0xFFFFFFFF),
49 ("16_16_UINT", 27, "uint", 0xFFFFFFFF),
50 ("16_16_SINT", 28, "sint", 0xFFFFFFFF),
51 ("16_16_FLOAT", 29, "f16", 0xFFFFFFFF),
52 ("32_32_UINT", 62, "u32", None),
53 ("32_32_SINT", 63, "i32", None),
54 ("32_32_FLOAT", 64, "f32", None),
55)
56
57SEL_VALS = (0, 1, 4, 5, 6, 7)
58SEL_XY01 = (4, 5, 0, 1)
59SEL_XYZW = (4, 5, 6, 7)
60SEL_X001 = (4, 0, 0, 1)
61
62
63def f32_to_u32(val):
64 return struct.unpack("<I", struct.pack("<f", val))[0]
65
66
67def u32_to_f32(bits):
68 return struct.unpack("<f", struct.pack("<I", bits))[0]
69
70
71def vsharp_d3(code, sel=SEL_XYZW):
72 sx, sy, sz, sw = sel
73 return sx | (sy << 3) | (sz << 6) | (sw << 9) | (code << 12) | (1 << 24) | (3 << 28)
74
75
76def round_half_away(frac):
77 """Exact round to nearest integer, ties away from zero."""
78 if frac >= 0:
79 return int(frac + Fraction(1, 2))
80 return -int(-frac + Fraction(1, 2))
81
82
83def model_norm(u_bits, kind, bits):
84 """Exact single-rounded UNORM/SNORM encoding (ties away from zero, NaN -> 0)."""
85 f = u32_to_f32(u_bits)
86 if f != f:
87 return 0
88 mask = (1 << bits) - 1
89 if kind == "unorm":
90 if f <= 0.0:
91 return 0
92 if f >= 1.0:
93 return mask
94 return round_half_away(Fraction(f) * mask)
95 scale = (1 << (bits - 1)) - 1
96 if f <= -1.0:
97 return (-scale) & mask
98 if f >= 1.0:
99 return scale
100 return round_half_away(Fraction(f) * scale) & mask
101
102
103def model_norm_double(u_bits, kind, bits):
104 """Double-rounded f32-multiply + RoundEven encoding (pre-SHADER-364 translator behaviour)."""
105 f = u32_to_f32(u_bits)
106 if f != f:
107 return 0
108 mask = (1 << bits) - 1
109 if kind == "unorm":
110 f = max(0.0, min(1.0, f))
111 prod = u32_to_f32(f32_to_u32(f * float(mask)))
112 return int(round(prod))
113 scale = (1 << (bits - 1)) - 1
114 f = max(-1.0, min(1.0, f))
115 prod = u32_to_f32(f32_to_u32(f * float(scale)))
116 return int(round(prod)) & mask
117
118
119def model_2comp_channels(sel, comps):
120 """Hardware 2-component MUBUF store COMP_SWAP rule from V# DST_SEL (sx, sy, sz, sw).
121
122 comps is the 4-tuple (x, y, z, w) padded with 0 for absent store components.
123 Returns (mem_ch0, mem_ch1).
124 """
125 sx, sy, sz, _sw = sel
126 use_y = (sy >= 4) and (sz < 4)
127 rev = (sx != 4) and ((sy >= 4) or (sz >= 4))
128 sec = comps[1] if use_y else comps[3]
129 return (sec, comps[0]) if rev else (comps[0], sec)
130
131
132def norm_inputs(kind, bits):
133 """Specials + inputs near (k + 0.5) / scale that expose double rounding."""
134 scale = (1 << bits) - 1 if kind == "unorm" else (1 << (bits - 1)) - 1
135 out = [
136 0x00000000, 0x80000000, 0x00000001, 0x80000001,
137 0x007FFFFF, 0x807FFFFF, 0x00800000, 0x80800000,
138 f32_to_u32(0.5), f32_to_u32(-0.5),
139 f32_to_u32(0.3), f32_to_u32(-0.3),
140 f32_to_u32(1.0), f32_to_u32(-1.0),
141 f32_to_u32(1.5), f32_to_u32(-1.5),
142 0x7F800000, 0xFF800000, 0x7FC00000, 0xFFC00000,
143 0x7F800001, 0xFF800001,
144 ]
145 step = max(1, scale // 100)
146 for k in range(0, scale, step):
147 base = f32_to_u32((k + 0.5) / scale)
148 for d in (-1, 0, 1):
149 out.append(base + d)
150 if kind == "snorm":
151 out.append((base + d) | 0x80000000)
152 return out
153
154
155def _store_kernel(asm_mod, inst, code, sel, vals, wave):
156 n_comp = len(inst.rsplit("_", 1)[1])
157 vreg = "v4" if n_comp == 1 else f"v[4:{3 + n_comp}]"
158 st = (f"{inst} {vreg}, v1, s[8:11], 0 offen glc" if inst.startswith("buffer_")
159 else f"{inst} {vreg}, v1, s[8:11], 0 format:{code} offen glc")
160 lines = [
161 "v_mov_b32 v1, 0",
162 "s_mov_b32 s8, s2",
163 "s_and_b32 s9, s3, 0xffff",
164 "s_mov_b32 s10, 0x100",
165 f"s_mov_b32 s11, 0x{vsharp_d3(code, sel):x}",
166 ]
167 for i, v in enumerate(vals[:n_comp]):
168 lines.append(f"v_mov_b32 v{4 + i}, 0x{v:x}")
169 lines += [st, "s_waitcnt_vscnt null, 0x0", "s_endpgm"]
170 return asm_mod.Kernel(lines, wave, 1, 2, raw=True, vgprs=12, sgprs=16)
171
172
173def probe_norm(oracle, asm_mod, wave):
174 """Run UNORM/SNORM rounding sweep + SNORM2 tie check in wave32 or wave64."""
175 report = {}
176 for name, code, kind, bits in NORM_FORMATS:
177 inputs = norm_inputs(kind, bits)
178 mask = (1 << bits) - 1
179 sel = SEL_XYZW if bits == 10 else SEL_X001
180 fmt_res = {}
181 for inst in ("buffer_store_format_x", "tbuffer_store_format_x"):
182 ks = [_store_kernel(asm_mod, inst, code, sel, (u,), wave) for u in inputs]
183 got = oracle.run(ks, words=2)
184 exact_ok = double_diffs = 0
185 first_bad = None
186 for u, words in zip(inputs, got):
187 if isinstance(words, str) or len(words) < 2:
188 raise RuntimeError(f"{name} {inst} wave{wave}: {words}")
189 hw = words[0] & mask
190 want = model_norm(u, kind, bits)
191 dbl = model_norm_double(u, kind, bits)
192 if want != dbl:
193 double_diffs += 1
194 if hw == want:
195 exact_ok += 1
196 elif first_bad is None:
197 first_bad = {"f32": f"{u:#010x}", "hw": hw, "want": want, "double": dbl}
198 fmt_res[inst] = {"inputs": len(inputs), "exact": exact_ok, "double_witnesses": double_diffs,
199 "first_mismatch": first_bad}
200 report[name] = fmt_res
201 # SNORM2 tie-breaking on code 45 (10_10_10_2_SNORM: 2-bit x at bits [1:0])
202 tie_vals = (f32_to_u32(0.5), f32_to_u32(-0.5), f32_to_u32(0.5) - 1, f32_to_u32(-0.5) - 1)
203 ks = [_store_kernel(asm_mod, "buffer_store_format_xyzw", 45, SEL_XYZW, (u, 0, 0, 0), wave) for u in tie_vals]
204 got = oracle.run(ks, words=2)
205 tie_ok = sum((w[0] & 3) == model_norm(u, "snorm", 2) for u, w in zip(tie_vals, got))
206 report["snorm2_ties"] = {"inputs": len(tie_vals), "exact": tie_ok,
207 "half_pos": got[0][0] & 3, "half_neg": got[1][0] & 3}
208 return report
209
210
211def probe_two_comp(oracle, asm_mod, wave):
212 """Run all 12 2-component formats (XY01 vs XYZW, MUBUF vs MTBUF) + all 216 (sx,sy,sz) triples on 32_32_UINT."""
213 int_vals = (0x11, 0x22, 0x33, 0x44)
214 flt_vals = (f32_to_u32(0.25), f32_to_u32(0.5), f32_to_u32(0.75), f32_to_u32(1.0))
215 formats_ok = 0
216 format_mismatches = []
217 for fname, code, kind, mask in TWO_COMP_FORMATS:
218 vals = flt_vals if kind in ("unorm", "snorm", "f16", "f32") else int_vals
219 cases = (
220 ("mubuf_xy_XY01", "buffer_store_format_xy", SEL_XY01),
221 ("mubuf_xyzw_XY01", "buffer_store_format_xyzw", SEL_XY01),
222 ("mubuf_xy_XYZW", "buffer_store_format_xy", SEL_XYZW),
223 ("mubuf_xyzw_XYZW", "buffer_store_format_xyzw", SEL_XYZW),
224 ("mtbuf_xyzw_XYZW", "tbuffer_store_format_xyzw", SEL_XYZW),
225 )
226 ks = [_store_kernel(asm_mod, inst, code, sel, vals, wave) for _, inst, sel in cases]
227 got = oracle.run(ks, words=2)
228 if any(isinstance(w, str) or len(w) < 2 for w in got):
229 raise RuntimeError(f"{fname} wave{wave}: {got}")
230 # Reference: mubuf_xy_XY01 == mubuf_xyzw_XY01 == mtbuf_xyzw_XYZW == (x, y),
231 # mubuf_xy_XYZW == (x, 0), mubuf_xyzw_XYZW == (x, w) (distinct from (x, y) and (x, 0))
232 def elem(w):
233 return (w[0] & mask,) if mask is not None else (w[0], w[1])
234 xy_xy01, xyzw_xy01, xy_xyzw, xyzw_xyzw, mt_xyzw = (elem(w) for w in got)
235 if xy_xy01 == xyzw_xy01 == mt_xyzw and xy_xyzw != xy_xy01 and xyzw_xyzw != xy_xy01 and xyzw_xyzw != xy_xyzw:
236 formats_ok += 1
237 else:
238 format_mismatches.append({"format": fname, "xy_xy01": xy_xy01, "xyzw_xy01": xyzw_xy01,
239 "xy_xyzw": xy_xyzw, "xyzw_xyzw": xyzw_xyzw, "mt_xyzw": mt_xyzw})
240 # Exhaustive 216 (sx, sy, sz) triples on 32_32_UINT (code 62)
241 triples = list(itertools.product(SEL_VALS, repeat=3))
242 ks = [_store_kernel(asm_mod, "buffer_store_format_xyzw", 62, (sx, sy, sz, 1), int_vals, wave)
243 for sx, sy, sz in triples]
244 got = oracle.run(ks, words=2)
245 triples_ok = 0
246 triple_bad = []
247 for (sx, sy, sz), w in zip(triples, got):
248 if isinstance(w, str) or len(w) < 2:
249 raise RuntimeError(f"32_32_UINT ({sx},{sy},{sz}) wave{wave}: {w}")
250 want = model_2comp_channels((sx, sy, sz, 1), int_vals)
251 if (w[0], w[1]) == want:
252 triples_ok += 1
253 elif len(triple_bad) < 4:
254 triple_bad.append({"sel": [sx, sy, sz, 1], "hw": [w[0], w[1]], "want": list(want)})
255 return {
256 "formats_total": len(TWO_COMP_FORMATS),
257 "formats_ok": formats_ok,
258 "format_mismatches": format_mismatches,
259 "triples_total": len(triples),
260 "triples_ok": triples_ok,
261 "triple_mismatches": triple_bad,
262 }
263
264
265def self_test():
266 # Double-rounding witness: UNORM16(0.3) -> exact 19661, double-rounded 19660
267 u03 = f32_to_u32(0.3)
268 assert model_norm(u03, "unorm", 16) == 19661
269 assert model_norm_double(u03, "unorm", 16) == 19660
270 # SNORM2 ties away from zero
271 assert model_norm(f32_to_u32(0.5), "snorm", 2) == 1
272 assert model_norm(f32_to_u32(-0.5), "snorm", 2) == 3
273 assert model_norm(0x7FC00000, "unorm", 16) == 0
274 assert model_norm(0xFFC00000, "snorm", 16) == 0
275 # 2-component COMP_SWAP truth table
276 c = (0x11, 0x22, 0x33, 0x44)
277 assert model_2comp_channels(SEL_XY01, c) == (0x11, 0x22)
278 assert model_2comp_channels((5, 4, 0, 1), c) == (0x22, 0x11)
279 assert model_2comp_channels(SEL_XYZW, c) == (0x11, 0x44)
280 assert model_2comp_channels((5, 4, 6, 7), c) == (0x44, 0x11)
281 assert model_2comp_channels(SEL_XYZW, (0x11, 0x22, 0, 0)) == (0x11, 0)
282 # Every norm format must have at least one double-rounding witness
283 for name, _code, kind, bits in NORM_FORMATS:
284 w = sum(model_norm(u, kind, bits) != model_norm_double(u, kind, bits) for u in norm_inputs(kind, bits))
285 assert w > 0, f"{name} has no double-rounding witness"
286 print("self-test OK")
287
288
289def main():
290 if hasattr(sys.stdout, "reconfigure"):
291 sys.stdout.reconfigure(encoding="utf-8", errors="replace")
292 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
293 ap.add_argument("--waves", default="32,64", help="wave sizes to run (default: 32,64)")
294 ap.add_argument("--json", dest="json_out", help="write full JSON report to this path")
295 ap.add_argument("--self-test", action="store_true", help="check the Python models without a GPU")
296 args = ap.parse_args()
297 if args.self_test:
298 self_test()
299 return 0
300 from hw_oracle import asm, runner
301 try:
302 oracle = runner.open_oracle()
303 except runner.Unavailable as exc:
304 print(f"SKIP: {exc}", file=sys.stderr)
305 return 77
306 if asm.family(oracle.arch) != "gfx10":
307 print(f"SKIP: {oracle.arch} is not GFX10 (RDNA1/RDNA2)", file=sys.stderr)
308 return 77
309 waves = [int(w) for w in args.waves.split(",") if w.strip()]
310 out = {"arch": oracle.arch, "waves": {}}
311 mismatches = 0
312 for wave in waves:
313 norm = probe_norm(oracle, asm, wave)
314 two = probe_two_comp(oracle, asm, wave)
315 out["waves"][str(wave)] = {"norm": norm, "two_comp": two}
316 for name, _code, _kind, _bits in NORM_FORMATS:
317 for inst, info in norm[name].items():
318 if info["exact"] != info["inputs"]:
319 mismatches += 1
320 if norm["snorm2_ties"]["exact"] != norm["snorm2_ties"]["inputs"]:
321 mismatches += 1
322 if two["formats_ok"] != two["formats_total"] or two["triples_ok"] != two["triples_total"]:
323 mismatches += 1
324 print(f"wave{wave} ({oracle.arch}): norm exact across {len(NORM_FORMATS)} formats + snorm2 ties, "
325 f"2-comp {two['formats_ok']}/{two['formats_total']} formats, "
326 f"{two['triples_ok']}/{two['triples_total']} DST_SEL triples")
327 if args.json_out:
328 with open(args.json_out, "w", encoding="utf-8", newline="\n") as f:
329 json.dump(out, f, indent=2)
330 return 1 if mismatches else 0
331
332
333if __name__ == "__main__":
334 if hasattr(sys.stdout, "reconfigure"):
335 sys.stdout.reconfigure(errors="replace")
336 raise SystemExit(main())
diff --git a/tools/buffer_swizzle_probe.py b/tools/buffer_swizzle_probe.py
new file mode 100644
index 000000000..16c5c8a75
--- /dev/null
+++ b/tools/buffer_swizzle_probe.py
@@ -0,0 +1,665 @@
1r"""SHADER-343: Native RDNA2 hardware probe for swizzled buffer addressing (V# SWIZZLE_ENABLE, ADD_TID_ENABLE).
2
3Runs self-contained MUBUF/MTBUF buffer-swizzle kernels natively on an AMD GPU through tools/hw_oracle (wave32 and
4wave64) and compares every output word with Leonida's live translator (tools/rdna2spirv.py ->
5tests/semantic/spirv_mini_interp.py). Standard library only; no game files.
6
7Groups covered (docs/design.md, Swizzled buffer addressing):
8 swizzle_basic IS=8/16/32/64 formula, index >= IS, non-4-mult stride, inst_offset, mode 0 soffset, stride 0
9 idxen_ignores_tid idxen=1 ignores ADD_TID_ENABLE (linear & swizzled, address & bounds, load/typed/atomic)
10 swizzle_activation SWIZZLE_ENABLE=1 with idxen=0 and ADD_TID_ENABLE=0 stays linear and RAW in mode 3
11 multi_dword_stepping scratch swizzle (+4*IS) vs indexed swizzle (+4 linear, crossing IS), loads/stores & per-dword OOB
12 typed_and_atomic_x2 scratch swizzle suppresses typed >4B & atomic_*_x2 even in mode 2; indexed swizzle steps +4
13 oob_mode3_soffset OOB_SELECT 3 with active swizzle and stride != 0 checks (index + soffset) >= num_records
14 offset_wrap uint32(voff + inst_offset) wraps at 32 bits; RAW mode 3 uint64(off) + uint64(soff) does not
15 add_tid_wave_lane 64-thread ADD_TID_ENABLE wraps at wave lane 32 on wave32 vs 64 on wave64
16
17Usage:
18 python -I tools/buffer_swizzle_probe.py # translator side only (CPU)
19 python -I tools/buffer_swizzle_probe.py --oracle hw # native AMD GPU only (wave32 + wave64)
20 python -I tools/buffer_swizzle_probe.py --oracle both # compare hardware vs translator
21 python -I tools/buffer_swizzle_probe.py --oracle both --strict # fail on known divergences too
22 python -I tools/buffer_swizzle_probe.py --self-test
23
24Exit codes:
25 0 all unexpected comparisons match (and wave32 == wave64 on wave-invariant cases)
26 1 at least one unexpected mismatch, unexpected wave32/64 diff, or known divergence under --strict
27 2 bad CLI arguments or harness error
28 77 hardware oracle requested but unavailable on this machine
29"""
30import argparse
31import json
32import os
33import struct
34import sys
35import tempfile
36import warnings
37
38HERE = os.path.dirname(os.path.abspath(__file__))
39ROOT = os.path.dirname(HERE)
40sys.dont_write_bytecode = True
41for p in (HERE, os.path.join(ROOT, "tests", "semantic")):
42 if p not in sys.path:
43 sys.path.insert(0, p)
44
45import rdna2spirv # noqa: E402
46import spirv_mini_interp # noqa: E402
47
48# Buffer layout in the allocated buffer (s[0:3] RAW V# at offset 0):
49# 0x000..0x0FF (64 dwords): output words out[0..63]
50# 0x100..0x7FF (448 dwords): data region DATA_BASE (s[16:17]), seeded with 0x5EED0000 + offset
51OUT_WORDS = 512
52DATA_OFF = 0x100
53DATA_DWORDS = OUT_WORDS - (DATA_OFF // 4)
54SEED_BASE = 0x5EED0000
55OUT_V_W3 = 0x31016FAC
56V_W3_BASE = 0x01000FAC
57
58KNOWN_DIVERGENCES = {}
59
60
61def _cs_fssm(threads):
62 header = bytearray(0x148)
63 struct.pack_into("<4I", header, 0x138, 0x8088, threads, 1, 1)
64 return bytes(header)
65
66
67def _vsharp_lines(stride, nr, istride, mode, *, swz=True, tid=False, fmt=22):
68 """Build probed V# in s[4:7] anchored at DATA_BASE (s[16:17])."""
69 w1_hi = (stride << 16) | (int(swz) << 31)
70 w3 = V_W3_BASE | (fmt << 12) | (istride << 21) | (int(tid) << 23) | (mode << 28)
71 return [
72 "s_mov_b32 s4, s16",
73 f"s_or_b32 s5, s17, {w1_hi:#x}",
74 f"s_mov_b32 s6, {nr:#x}",
75 f"s_mov_b32 s7, {w3:#x}",
76 ]
77
78
79class Case:
80 """One self-contained buffer-swizzle probe kernel.
81
82 `body` runs after s[0:3] is the RAW output V# (base 0) and s[16:17] is DATA_BASE (base + 0x100), with the data
83 region seeded to `0x5EED0000 + byte_offset`. `body` stores `words` output dwords into out[0..words-1] via s[0:3].
84 """
85
86 __slots__ = ("group", "name", "body", "note", "threads", "words", "wave_dependent")
87
88 def __init__(self, group, name, body, note="", *, threads=1, words=4, wave_dependent=False):
89 self.group = group
90 self.name = name
91 self.body = tuple(body)
92 self.note = note
93 self.threads = threads
94 self.words = words
95 self.wave_dependent = wave_dependent
96
97
98def _single_lane(lines):
99 return ["v_cmpx_eq_u32_e32 0, v0", *lines]
100
101
102def build_cases():
103 cases = []
104
105 # 1. Baseline swizzled addressing formula (IS=8/16/32/64, index>=IS, non-4-mult stride, inst_offset, mode 0 soffset)
106 cases += [
107 Case("swizzle_basic", "is8_idx_off", _single_lane([
108 *_vsharp_lines(8, 16, 0, 3),
109 "v_mov_b32 v1, 1", "v_mov_b32 v2, 4",
110 "buffer_load_dword v8, v[1:2], s[4:7], 0 idxen offen", # (0*8+4)*8 + 1*4 = 0x24
111 "v_mov_b32 v1, 9", "v_mov_b32 v2, 0",
112 "buffer_load_dword v9, v[1:2], s[4:7], 0 idxen offen", # (1*8+0)*8 + 1*4 = 0x44
113 "v_mov_b32 v1, 1",
114 "buffer_load_dword v10, v1, s[4:7], 0 idxen offset:4", # inst_offset=4 -> 0x24
115 *_vsharp_lines(8, 4, 0, 1),
116 "v_mov_b32 v1, 3", "v_mov_b32 v2, 0x20",
117 "buffer_load_dword v11, v[1:2], s[4:7], 0 idxen offen", # mode 1: (0*8+0x20)*8 + 3*4 = 0x10c
118 "s_waitcnt vmcnt(0)",
119 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
120 ]), "IS=8 idx/off, idx>=IS, inst_offset, and mode 1 large off"),
121
122 Case("swizzle_basic", "is16_32_64_non4_stride", _single_lane([
123 *_vsharp_lines(8, 8, 1, 0), # IS=16
124 "v_mov_b32 v1, 3", "v_mov_b32 v2, 4",
125 "buffer_load_dword v8, v[1:2], s[4:7], 0 idxen offen", # (0*8+4)*16 + 3*4 = 0x4c
126 *_vsharp_lines(16, 64, 2, 1), # IS=32
127 "v_mov_b32 v1, 35", "v_mov_b32 v2, 4",
128 "buffer_load_dword v9, v[1:2], s[4:7], 0 idxen offen", # (1*16+4)*32 + 3*4 = 0x28c
129 *_vsharp_lines(8, 100, 3, 1), # IS=64
130 "v_mov_b32 v1, 65",
131 "buffer_load_dword v10, v1, s[4:7], 0 idxen", # (1*8)*64 + 1*4 = 0x204
132 *_vsharp_lines(18, 16, 0, 0), # IS=8, non-4-multiple stride 18
133 "v_mov_b32 v1, 9", "v_mov_b32 v2, 4",
134 "buffer_load_dword v11, v[1:2], s[4:7], 0 idxen offen", # (1*18+4)*8 + 1*4 = 0xb4
135 "s_waitcnt vmcnt(0)",
136 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
137 ]), "IS=16/32/64 and non-4-multiple stride 18"),
138
139 Case("swizzle_basic", "stride0_and_mode0_soff", _single_lane([
140 *_vsharp_lines(0, 0x40, 0, 3), # stride=0, idxen=1: swizzled addr + RAW check
141 "v_mov_b32 v1, 2", "v_mov_b32 v2, 0x30",
142 "buffer_load_dword v8, v[1:2], s[4:7], 0 idxen offen", # (0*0+0x30)*8 + 2*4 = 0x188
143 *_vsharp_lines(8, 16, 0, 0), # mode 0: soffset added after swizzle, not checked
144 "s_mov_b32 s8, 0x100",
145 "v_mov_b32 v1, 1", "v_mov_b32 v2, 4",
146 "buffer_load_dword v9, v[1:2], s[4:7], s8 idxen offen", # 0x24 + 0x100 = 0x124
147 *_vsharp_lines(8, 4, 0, 2), # mode 2: disabled bounds
148 "v_mov_b32 v1, 5",
149 "buffer_load_dword v10, v1, s[4:7], 0 idxen", # 5*4 = 0x14
150 *_vsharp_lines(8, 16, 0, 0), # mode 0: idx 16 >= 16 -> OOB
151 "v_mov_b32 v1, 16",
152 "buffer_load_dword v11, v1, s[4:7], 0 idxen", # 0
153 "s_waitcnt vmcnt(0)",
154 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
155 ]), "stride=0 RAW with idxen, mode 0 soffset, mode 2, and mode 0 OOB"),
156 ]
157
158 # 2. idxen == 1 ignores ADD_TID_ENABLE (linear & swizzled, address & bounds, load/typed/atomic)
159 cases += [
160 Case("idxen_ignores_tid", "linear_idxen_tid", [
161 *_vsharp_lines(4, 5, 0, 1, swz=False, tid=True),
162 "v_mov_b32 v1, 2",
163 "buffer_load_dword v8, v1, s[4:7], 0 idxen", # every lane reads idx=2 (< 5) -> 0x08
164 "s_waitcnt vmcnt(0)",
165 "v_lshlrev_b32 v2, 2, v0",
166 "buffer_store_dword v8, v2, s[0:3], 0 offen",
167 ], "linear idxen=1 ignores ADD_TID_ENABLE for both address and bounds", threads=8, words=8),
168
169 Case("idxen_ignores_tid", "swizzled_idxen_tid", [
170 *_vsharp_lines(8, 16, 0, 3, swz=True, tid=True),
171 "v_mov_b32 v1, 4",
172 "buffer_load_dword v8, v1, s[4:7], 0 idxen", # every lane reads idx=4 -> 0x10
173 "s_waitcnt vmcnt(0)",
174 "v_lshlrev_b32 v2, 2, v0",
175 "buffer_store_dword v8, v2, s[0:3], 0 offen",
176 ], "swizzled idxen=1 ignores ADD_TID_ENABLE across lanes", threads=8, words=8),
177
178 Case("idxen_ignores_tid", "typed_and_atomic_idxen_tid", [
179 "v_cmpx_eq_u32_e32 3, v0", # run on lane 3 so lane != 0
180 *_vsharp_lines(8, 16, 0, 0, swz=True, tid=True, fmt=20),
181 "v_mov_b32 v1, 1",
182 "buffer_load_format_x v8, v1, s[4:7], 0 idxen", # idx=1 -> 0x04
183 "v_mov_b32 v1, 2",
184 "tbuffer_load_format_x v9, v1, s[4:7], 0 format:[BUF_FMT_32_UINT] idxen", # idx=2 -> 0x08
185 "v_mov_b32 v1, 3", "v_mov_b32 v10, 0x77777777",
186 "buffer_atomic_swap v10, v1, s[4:7], 0 idxen glc", # idx=3 -> old 0x0c
187 "s_waitcnt vmcnt(0)",
188 "buffer_load_dword v11, off, s[0:3], 0 offset:0x10c", # verify swap wrote 0x0c, not (3+3)*4=0x18
189 "s_waitcnt vmcnt(0)",
190 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
191 ], "lane 3 typed MUBUF, MTBUF, and atomic with idxen=1 ignore ADD_TID_ENABLE", threads=4, words=4),
192 ]
193
194 # 3. SWIZZLE_ENABLE=1 with idxen=0 and ADD_TID_ENABLE=0 has zero effect (linear + mode 3 stays RAW)
195 cases += [
196 Case("swizzle_activation", "no_idx_no_tid_linear", _single_lane([
197 *_vsharp_lines(8, 4, 0, 1, swz=True, tid=False),
198 "v_mov_b32 v1, 0x10",
199 "buffer_load_dword v8, v1, s[4:7], 0 offen", # linear 0x10 (not 0x80)
200 *_vsharp_lines(8, 0x40, 0, 3, swz=True, tid=False),
201 "v_mov_b32 v1, 0x30",
202 "buffer_load_dword v9, v1, s[4:7], 0 offen", # stays RAW linear 0x30 despite stride 8
203 *_vsharp_lines(0x40, 4, 0, 0, swz=True, tid=False),
204 "v_mov_b32 v1, 0x10",
205 "buffer_load_dword v10, v1, s[4:7], 0 offen", # mode 0 linear 0x10
206 *_vsharp_lines(8, 4, 0, 2, swz=True, tid=False),
207 "v_mov_b32 v1, 0x10",
208 "buffer_load_dword v11, v1, s[4:7], 0 offen", # mode 2 linear 0x10
209 "s_waitcnt vmcnt(0)",
210 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
211 ]), "SWIZZLE_ENABLE=1 with idxen=0 and ADD_TID_ENABLE=0 stays linear across modes 0..3"),
212 ]
213
214 # 4. Multi-dword stepping: scratch swizzle (+4*IS) vs indexed swizzle (+4 linear)
215 cases += [
216 Case("multi_dword_stepping", "scratch_swz_load_x4", [
217 "v_cmpx_eq_u32_e32 2, v0",
218 *_vsharp_lines(16, 4, 0, 0, swz=True, tid=True), # IS=8, lane=2 -> 0x08, 0x28, 0x48, 0x68
219 "buffer_load_dwordx4 v[8:11], off, s[4:7], 0",
220 "s_waitcnt vmcnt(0)",
221 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
222 ], "scratch swizzle (idxen=0, ADD_TID=1) x4 load steps by +4*IS", threads=4, words=4),
223
224 Case("multi_dword_stepping", "scratch_swz_load_x4_oob", [
225 "v_cmpx_eq_u32_e32 2, v0",
226 *_vsharp_lines(8, 4, 0, 0, swz=True, tid=True), # stride=8: dwords 0..1 IN, 2..3 OOB
227 "buffer_load_dwordx4 v[8:11], off, s[4:7], 0",
228 "s_waitcnt vmcnt(0)",
229 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
230 ], "scratch swizzle x4 load per-dword OOB at stride=8", threads=4, words=4),
231
232 Case("multi_dword_stepping", "scratch_swz_store_x2", [
233 "v_cmpx_eq_u32_e32 5, v0",
234 *_vsharp_lines(8, 16, 1, 3, swz=True, tid=True), # IS=16, lane=5 -> writes 0x14 and 0x54
235 "v_mov_b32 v1, 0xaaaa0001", "v_mov_b32 v2, 0xaaaa0002",
236 "buffer_store_dwordx2 v[1:2], off, s[4:7], 0",
237 "s_waitcnt vmcnt(0)",
238 "buffer_load_dword v8, off, s[0:3], 0 offset:0x114",
239 "buffer_load_dword v9, off, s[0:3], 0 offset:0x118",
240 "buffer_load_dword v10, off, s[0:3], 0 offset:0x154",
241 "buffer_load_dword v11, off, s[0:3], 0 offset:0x158",
242 "s_waitcnt vmcnt(0)",
243 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
244 ], "scratch swizzle x2 store steps by +4*IS (IS=16 -> +0x40)", threads=8, words=4),
245
246 Case("multi_dword_stepping", "indexed_swz_load_x4", _single_lane([
247 *_vsharp_lines(16, 4, 0, 0, swz=True, tid=False), # IS=8, idx=2 -> 0x08, 0x0c, 0x10, 0x14
248 "v_mov_b32 v1, 2",
249 "buffer_load_dwordx4 v[8:11], v1, s[4:7], 0 idxen",
250 "s_waitcnt vmcnt(0)",
251 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
252 ]), "indexed swizzle (idxen=1) x4 load steps linearly by +4"),
253
254 Case("multi_dword_stepping", "indexed_swz_load_x2_cross_is_and_oob", _single_lane([
255 *_vsharp_lines(8, 16, 0, 3, swz=True, tid=True), # IS=8, idx=7 -> 0x1c, 0x20 (linear across IS)
256 "v_mov_b32 v1, 7",
257 "buffer_load_dwordx2 v[8:9], v1, s[4:7], 0 idxen",
258 *_vsharp_lines(8, 16, 1, 3, swz=True, tid=False), # IS=16, idx=5, off=4 -> 0x54, 0 (dword 1 OOB)
259 "v_mov_b32 v1, 5", "v_mov_b32 v2, 4",
260 "buffer_load_dwordx2 v[10:11], v[1:2], s[4:7], 0 idxen offen",
261 "s_waitcnt vmcnt(0)",
262 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
263 ]), "indexed swizzle x2 crosses IS=8 linearly and enforces per-dword stride OOB"),
264
265 Case("multi_dword_stepping", "indexed_swz_store_x2", _single_lane([
266 *_vsharp_lines(8, 16, 0, 3, swz=True, tid=False), # IS=8, idx=2 -> writes 0x08 and 0x0c
267 "v_mov_b32 v1, 2", "v_mov_b32 v2, 0xbbbb0001", "v_mov_b32 v3, 0xbbbb0002",
268 "buffer_store_dwordx2 v[2:3], v1, s[4:7], 0 idxen",
269 "s_waitcnt vmcnt(0)",
270 "buffer_load_dword v8, off, s[0:3], 0 offset:0x108",
271 "buffer_load_dword v9, off, s[0:3], 0 offset:0x10c",
272 "buffer_load_dword v10, off, s[0:3], 0 offset:0x128",
273 "buffer_load_dword v11, off, s[0:3], 0 offset:0x12c",
274 "s_waitcnt vmcnt(0)",
275 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
276 ]), "indexed swizzle x2 store steps linearly by +4 (leaves +4*IS untouched)"),
277 ]
278
279 # 5. Typed formats and buffer_atomic_*_x2 in indexed vs scratch swizzle
280 cases += [
281 Case("typed_and_atomic_x2", "indexed_swz_fmt16_load", _single_lane([
282 *_vsharp_lines(16, 4, 0, 1, swz=True, tid=False, fmt=75), # 32_32_32_32_UINT, idx=1 -> 0x04..0x10
283 "v_mov_b32 v1, 1",
284 "buffer_load_format_xyzw v[8:11], v1, s[4:7], 0 idxen",
285 "s_waitcnt vmcnt(0)",
286 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
287 ]), "indexed swizzle 16B typed load steps linearly by +4"),
288
289 Case("typed_and_atomic_x2", "indexed_swz_fmt16_store", _single_lane([
290 *_vsharp_lines(16, 4, 0, 1, swz=True, tid=False, fmt=75),
291 "v_mov_b32 v1, 1",
292 "v_mov_b32 v2, 0xcccc0001", "v_mov_b32 v3, 0xcccc0002",
293 "v_mov_b32 v4, 0xcccc0003", "v_mov_b32 v5, 0xcccc0004",
294 "buffer_store_format_xyzw v[2:5], v1, s[4:7], 0 idxen",
295 "s_waitcnt vmcnt(0)",
296 "buffer_load_dword v8, off, s[0:3], 0 offset:0x104",
297 "buffer_load_dword v9, off, s[0:3], 0 offset:0x108",
298 "buffer_load_dword v10, off, s[0:3], 0 offset:0x124",
299 "buffer_load_dword v11, off, s[0:3], 0 offset:0x144",
300 "s_waitcnt vmcnt(0)",
301 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
302 ]), "indexed swizzle 16B typed store writes contiguous dwords"),
303
304 Case("typed_and_atomic_x2", "scratch_swz_fmt16_suppressed", [
305 "v_cmpx_eq_u32_e32 5, v0",
306 *_vsharp_lines(16, 16, 0, 2, swz=True, tid=True, fmt=75), # mode 2 (DISABLED), yet suppressed -> all 0
307 "buffer_load_format_xyzw v[8:11], off, s[4:7], 0",
308 "s_waitcnt vmcnt(0)",
309 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
310 ], "scratch swizzle suppresses 16B typed MUBUF load even in OOB_SELECT 2", threads=8, words=4),
311
312 Case("typed_and_atomic_x2", "scratch_swz_mtbuf_atomic_x2_and_4b_ctrl", [
313 "v_cmpx_eq_u32_e32 4, v0", # lane 4 -> addr +0x10 (8-byte aligned)
314 *_vsharp_lines(16, 16, 0, 2, swz=True, tid=True, fmt=20), # mode 2, 32_UINT (4B) in V#
315 "tbuffer_load_format_xy v[2:3], off, s[4:7], 0 format:[BUF_FMT_32_32_UINT]", # 8B -> suppressed (0, 0)
316 "v_mov_b32 v4, 0xeeeeeeee", "v_mov_b32 v5, 0xffffffff",
317 "buffer_atomic_swap_x2 v[4:5], off, s[4:7], 0 glc", # 8B -> suppressed (0, 0, mem untouched)
318 "buffer_load_format_x v10, off, s[4:7], 0", # 4B control -> 0x5eed0010
319 "s_waitcnt vmcnt(0)",
320 "v_or_b32 v8, v2, v3", # 0
321 "v_or_b32 v9, v4, v5", # 0
322 "buffer_load_dword v11, off, s[0:3], 0 offset:0x110", # mem untouched -> 0x5eed0010
323 "s_waitcnt vmcnt(0)",
324 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
325 ], "scratch swizzle suppresses 8B MTBUF & atomic_swap_x2 while 4B typed control succeeds", threads=8, words=4),
326
327 Case("typed_and_atomic_x2", "indexed_swz_atomic_x2", _single_lane([
328 *_vsharp_lines(16, 16, 0, 0, swz=True, tid=False),
329 "v_mov_b32 v1, 2", # addr +0x08 (8-byte aligned)
330 "v_mov_b32 v8, 0xdddd0001", "v_mov_b32 v9, 0xdddd0002",
331 "buffer_atomic_swap_x2 v[8:9], v1, s[4:7], 0 idxen glc", # old [0x5eed0008, 0x5eed000c]
332 "s_waitcnt vmcnt(0)",
333 "buffer_load_dword v10, off, s[0:3], 0 offset:0x108", # new 0xdddd0001
334 "buffer_load_dword v11, off, s[0:3], 0 offset:0x10c", # new 0xdddd0002
335 "s_waitcnt vmcnt(0)",
336 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
337 ]), "indexed swizzle 8B buffer_atomic_swap_x2 executes linearly at aligned address"),
338 ]
339
340 # 6. OOB_SELECT 3 with active swizzle and stride != 0 checks (index + soffset) >= num_records
341 cases += [
342 Case("oob_mode3_soffset", "indexed_mode3_soff_edge", _single_lane([
343 *_vsharp_lines(8, 16, 0, 3, swz=True, tid=False),
344 "s_mov_b32 s8, 0x100",
345 "v_mov_b32 v1, 1", "v_mov_b32 v2, 4",
346 "buffer_load_dword v8, v[1:2], s[4:7], s8 idxen offen", # 1 + 0x100 >= 16 -> 0 (OOB)
347 "s_mov_b32 s8, 12",
348 "v_mov_b32 v1, 3", "v_mov_b32 v2, 4",
349 "buffer_load_dword v9, v[1:2], s[4:7], s8 idxen offen", # 3 + 12 = 15 < 16 -> 0x38
350 "v_mov_b32 v1, 4", "v_mov_b32 v2, 4",
351 "buffer_load_dword v10, v[1:2], s[4:7], s8 idxen offen", # 4 + 12 = 16 >= 16 -> 0 (OOB)
352 *_vsharp_lines(8, 14, 0, 3, swz=True, tid=False),
353 "s_mov_b32 s8, 8",
354 "v_mov_b32 v1, 5",
355 "buffer_load_dword v11, v1, s[4:7], s8 idxen", # 5 + 8 = 13 < 14 -> 0x14 + 8 = 0x1c
356 "s_waitcnt vmcnt(0)",
357 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
358 ]), "mode 3 swizzled with stride != 0 checks (index + soffset) < num_records"),
359
360 Case("oob_mode3_soffset", "scratch_mode3_soff_lanes", [
361 *_vsharp_lines(8, 10, 0, 3, swz=True, tid=True),
362 "s_mov_b32 s8, 4",
363 "buffer_load_dword v8, off, s[4:7], s8", # lanes 0..5 IN (lane+4 < 10), 6..15 OOB
364 "s_waitcnt vmcnt(0)",
365 "v_lshlrev_b32 v2, 2, v0",
366 "buffer_store_dword v8, v2, s[0:3], 0 offen",
367 ], "scratch swizzle mode 3 with soffset=4 and NR=10: lanes 0..5 IN, 6..15 OOB", threads=16, words=16),
368 ]
369
370 # 7. 32-bit wrap on uint32(voff + inst_offset) vs 64-bit no-wrap on RAW mode 3 (off + soffset)
371 cases += [
372 Case("offset_wrap", "voff_inst_wrap_and_soff_nowrap", _single_lane([
373 *_vsharp_lines(8, 16, 0, 3, swz=True, tid=False),
374 "v_mov_b32 v1, 1", "v_mov_b32 v2, 0xfffffffc",
375 "buffer_load_dword v8, v[1:2], s[4:7], 0 idxen offen offset:8", # off wraps to 4 -> 0x24
376 *_vsharp_lines(0, 0x40, 0, 3, swz=False, tid=False),
377 "v_mov_b32 v1, 0xfffffffc",
378 "buffer_load_dword v9, v1, s[4:7], 0 offen offset:8", # linear off wraps to 4 -> 0x04
379 *_vsharp_lines(0, 0xffffffff, 0, 3, swz=False, tid=False),
380 "s_mov_b32 s8, 0xfffffff0",
381 "v_mov_b32 v1, 0x20",
382 "buffer_load_dword v10, v1, s[4:7], s8 offen", # 0x20 + 0xfffffff0 = 0x100000010 -> OOB
383 *_vsharp_lines(0, 0xffffffff, 0, 3, swz=True, tid=False),
384 "v_mov_b32 v1, 1", "v_mov_b32 v2, 0x20",
385 "buffer_load_dword v11, v[1:2], s[4:7], s8 idxen offen", # swizzled stride=0 RAW -> OOB
386 "s_waitcnt vmcnt(0)",
387 "buffer_store_dwordx4 v[8:11], off, s[0:3], 0",
388 ]), "uint32(voff + inst_offset) wraps at 32 bits; RAW mode 3 off + soffset does not"),
389 ]
390
391 # 8. 64-thread ADD_TID_ENABLE uses wave lane (0..31 in wave32, 0..63 in wave64), not workgroup thread ID
392 cases += [
393 Case("add_tid_wave_lane", "tid_wave32_vs_wave64", [
394 *_vsharp_lines(8, 64, 0, 1, swz=True, tid=True),
395 "buffer_load_dword v8, off, s[4:7], 0",
396 "s_waitcnt vmcnt(0)",
397 "v_lshlrev_b32 v2, 2, v0",
398 "buffer_store_dword v8, v2, s[0:3], 0 offen",
399 ], "64 threads with ADD_TID_ENABLE: wave32 wraps lanes 32..63 to 0..31, wave64 uses 0..63",
400 threads=64, words=64, wave_dependent=True),
401 ]
402
403 return cases
404
405
406def _hw_kernel_lines(case, idx, wave):
407 """Wrap `case.body` for hw_oracle (raw=True, s[2:3] = output buffer base address)."""
408 lbl = f".Lseed_{idx}"
409 lbl_done = f".Lseed_done_{idx}"
410 # Build RAW V# in s[0:3] from s[2:3], compute DATA_BASE = base + DATA_OFF in s[16:17], and seed DATA_BASE on
411 # lane 0 (preserving EXEC with wave-sized save/restore so all threads participate in the body afterwards).
412 if wave == 32:
413 save_exec = ["s_mov_b32 s28, exec_lo", "v_cmpx_eq_u32_e32 0, v0"]
414 restore_exec = ["s_mov_b32 exec_lo, s28"]
415 else:
416 save_exec = ["s_mov_b64 s[28:29], exec", "v_cmpx_eq_u32_e32 0, v0"]
417 restore_exec = ["s_mov_b64 exec, s[28:29]"]
418 lines = [
419 "s_mov_b32 s0, s2",
420 "s_and_b32 s1, s3, 0xffff",
421 "s_mov_b32 s2, 0xffffffff",
422 f"s_mov_b32 s3, {OUT_V_W3:#x}",
423 f"s_add_u32 s16, s0, {DATA_OFF:#x}",
424 "s_addc_u32 s17, s1, 0",
425 "s_and_b32 s17, s17, 0xffff",
426 *save_exec,
427 "s_mov_b32 s20, 0",
428 f"{lbl}:",
429 f"s_cmp_ge_u32 s20, {DATA_DWORDS * 4:#x}",
430 f"s_cbranch_scc1 {lbl_done}",
431 f"s_add_u32 s21, s20, {SEED_BASE:#x}",
432 "v_mov_b32 v30, s21",
433 f"s_add_u32 s22, s20, {DATA_OFF:#x}",
434 "buffer_store_dword v30, off, s[0:3], s22",
435 "s_add_u32 s20, s20, 4",
436 f"s_branch {lbl}",
437 f"{lbl_done}:",
438 "s_waitcnt vmcnt(0)",
439 *restore_exec,
440 ]
441 if case.threads > 1:
442 lines.append("s_barrier")
443 lines.extend(case.body)
444 lines.append("s_endpgm")
445 return lines
446
447
448def _translate_case(work, case, wave=32):
449 os.makedirs(os.path.join(work, "disasm"), exist_ok=True)
450 os.makedirs(os.path.join(work, "fssm"), exist_ok=True)
451 name = f"cs_swz_probe_{case.name}_w{wave}"
452 src = os.path.join(work, "disasm", name + ".s")
453 wave_tag = "s_mov_b64 s[28:29], exec" if wave == 64 else "s_mov_b32 s28, exec_lo"
454 body = [
455 wave_tag,
456 f"s_add_u32 s16, s0, {DATA_OFF:#x}",
457 "s_addc_u32 s17, s1, 0",
458 "s_and_b32 s17, s17, 0xffff",
459 *case.body,
460 "s_endpgm",
461 ]
462 with open(src, "w", encoding="utf-8", newline="\n") as f:
463 f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in body))
464 with open(os.path.join(work, "fssm", name + ".fssm"), "wb") as f:
465 f.write(_cs_fssm(case.threads))
466 with warnings.catch_warnings():
467 warnings.simplefilter("ignore", ResourceWarning)
468 spv = rdna2spirv.translate(src)
469 memory = {a: 0 for a in range(0, DATA_OFF, 4)}
470 for off in range(0, DATA_DWORDS * 4, 4):
471 memory[DATA_OFF + off] = SEED_BASE + off
472 spirv_mini_interp.run_workgroup(
473 spv, case.threads, wave,
474 inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % wave},
475 push_constants=[0, 0, 0xFFFFFFFF, OUT_V_W3] + [0] * 28,
476 memory=memory,
477 )
478 return [memory.get(4 * i, 0) for i in range(case.words)]
479
480
481def run_translator(cases, waves=(32, 64)):
482 per_wave = {}
483 with tempfile.TemporaryDirectory(prefix="buf_swz_probe_") as work:
484 for wave in waves:
485 out = {}
486 for case in cases:
487 if wave != waves[0] and not case.wave_dependent:
488 out[case.name] = per_wave[waves[0]][case.name]
489 continue
490 try:
491 out[case.name] = _translate_case(work, case, wave=wave)
492 except Exception as e:
493 out[case.name] = f"error: {type(e).__name__}: {e}"
494 per_wave[wave] = out
495 return per_wave
496
497
498def run_hw(cases, arch=None, waves=(32, 64)):
499 from hw_oracle import asm, runner # noqa: E402
500 oracle = runner.open_oracle(arch=arch)
501 try:
502 device = oracle.device
503 per_wave = {}
504 for wave in waves:
505 kernels = [
506 asm.Kernel(_hw_kernel_lines(case, idx, wave), wave=wave, threads=case.threads,
507 words=OUT_WORDS, raw=True)
508 for idx, case in enumerate(cases)
509 ]
510 res = oracle.run(kernels, words=OUT_WORDS)
511 per_wave[wave] = {case.name: (r[:case.words] if isinstance(r, list) else r) for case, r in zip(cases, res)}
512 return device, per_wave
513 finally:
514 oracle.close()
515
516
517def _fmt_words(w):
518 if isinstance(w, list):
519 if len(w) <= 8:
520 return " ".join(f"0x{x:08x}" for x in w)
521 head = " ".join(f"0x{x:08x}" for x in w[:4])
522 tail = " ".join(f"0x{x:08x}" for x in w[-4:])
523 return f"[{len(w)} words: {head} ... {tail}]"
524 return str(w)
525
526
527def self_test():
528 cases = build_cases()
529 names = [c.name for c in cases]
530 assert len(names) == len(set(names)), "duplicate case names"
531 for name in KNOWN_DIVERGENCES:
532 assert name in names, f"unknown KNOWN_DIVERGENCES key: {name}"
533 res = run_translator(cases, waves=(32, 64))
534 for w in (32, 64):
535 errors = {k: v for k, v in res[w].items() if not isinstance(v, list)}
536 assert not errors, f"translator wave{w} errors: {errors}"
537 assert res[32]["tid_wave32_vs_wave64"] != res[64]["tid_wave32_vs_wave64"], "wave32/64 ADD_TID must differ"
538 print(f"self-test: {len(cases)} cases across {len({c.group for c in cases})} groups translated and ran on CPU OK")
539 return 0
540
541
542def main(argv=None):
543 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
544 ap.add_argument("--oracle", choices=("translator", "hw", "both"), default="translator")
545 ap.add_argument("--wave", choices=("32", "64", "both"), default="both")
546 ap.add_argument("--group", action="append", default=[], help="run only named group(s)")
547 ap.add_argument("--hw-arch", default=None, help="override GPU architecture for hw_oracle")
548 ap.add_argument("--list-groups", action="store_true")
549 ap.add_argument("--strict", action="store_true", help="treat known translator divergences as failures")
550 ap.add_argument("--json", dest="json_out", default=None, help="write raw results to a JSON file")
551 ap.add_argument("--self-test", action="store_true")
552 args = ap.parse_args(argv)
553
554 if args.self_test:
555 return self_test()
556
557 cases = build_cases()
558 groups = []
559 for c in cases:
560 if c.group not in groups:
561 groups.append(c.group)
562 if args.list_groups:
563 for g in groups:
564 n = sum(1 for c in cases if c.group == g)
565 print(f"{g:<22} ({n} cases)")
566 return 0
567
568 if args.group:
569 unknown = [g for g in args.group if g not in groups]
570 if unknown:
571 print(f"unknown group(s): {', '.join(unknown)}", file=sys.stderr)
572 return 2
573 want = set(args.group)
574 cases = [c for c in cases if c.group in want]
575
576 waves = (32, 64) if args.wave == "both" else (int(args.wave),)
577 tr_res = run_translator(cases, waves=waves) if args.oracle in ("translator", "both") else None
578 hw_device, hw_res = None, None
579 if args.oracle in ("hw", "both"):
580 from hw_oracle import runner # noqa: E402
581 try:
582 hw_device, hw_res = run_hw(cases, arch=args.hw_arch, waves=waves)
583 except runner.Unavailable as e:
584 print(f"hardware oracle unavailable: {e}", file=sys.stderr)
585 return 77
586 print(f"hardware oracle: {hw_device} (waves: {','.join(str(w) for w in waves)})")
587
588 mismatches = 0
589 known_diffs = 0
590 wave_diffs = 0
591 records = []
592 for c in cases:
593 t32 = tr_res[32][c.name] if tr_res and 32 in tr_res else None
594 t64 = tr_res[64][c.name] if tr_res and 64 in tr_res else None
595 h32 = hw_res[32][c.name] if hw_res and 32 in hw_res else None
596 h64 = hw_res[64][c.name] if hw_res and 64 in hw_res else None
597 status = "OK"
598 tag = None
599 if not c.wave_dependent and h32 is not None and h64 is not None and h32 != h64:
600 status = "WAVE_DIFF"
601 wave_diffs += 1
602 elif c.wave_dependent and h32 is not None and h64 is not None and h32 == h64:
603 status = "WAVE_SAME"
604 mismatches += 1
605 elif any(v is not None and not isinstance(v, list) for v in (t32, t64, h32, h64)):
606 status = "ERROR"
607 mismatches += 1
608 else:
609 bad = ((t32 is not None and h32 is not None and t32 != h32)
610 or (t64 is not None and h64 is not None and t64 != h64))
611 if bad:
612 hw_ref = h32 if h32 is not None else h64
613 known = KNOWN_DIVERGENCES.get(c.name)
614 if known and hw_ref == known[1]:
615 status = "KNOWN_DIFF"
616 tag = known[0]
617 known_diffs += 1
618 else:
619 status = "MISMATCH"
620 mismatches += 1
621 records.append({
622 "group": c.group, "name": c.name, "note": c.note, "wave_dependent": c.wave_dependent,
623 "status": status, "known_tag": tag,
624 "translator_w32": t32, "translator_w64": t64, "hw_w32": h32, "hw_w64": h64,
625 })
626 if status != "OK" or args.oracle != "both":
627 label = f"{status}:{tag}" if tag else status
628 print(f"[{label:<22}] {c.group}/{c.name}: {c.note}")
629 if h32 is not None:
630 print(f" hw_w32: {_fmt_words(h32)}")
631 if h64 is not None and h64 != h32:
632 print(f" hw_w64: {_fmt_words(h64)}")
633 if t32 is not None:
634 print(f" tr_w32: {_fmt_words(t32)}")
635 if t64 is not None and t64 != t32:
636 print(f" tr_w64: {_fmt_words(t64)}")
637
638 total = len(cases)
639 matched = total - mismatches - known_diffs - wave_diffs
640 print(f"summary: {total} cases: {matched} match, {known_diffs} known divergence, "
641 f"{mismatches} unexpected mismatch, {wave_diffs} wave32/64 diff")
642
643 if args.json_out:
644 out_path = os.path.abspath(args.json_out)
645 if os.path.isdir(out_path):
646 print(f"ERROR: --json path is a directory: {out_path}", file=sys.stderr)
647 return 2
648 parent = os.path.dirname(out_path)
649 if parent:
650 os.makedirs(parent, exist_ok=True)
651 with open(out_path, "w", encoding="utf-8", newline="\n") as f:
652 json.dump({"device": hw_device, "waves": list(waves), "cases": records}, f, indent=2)
653 f.write("\n")
654
655 if mismatches or wave_diffs or (args.strict and known_diffs):
656 return 1
657 return 0
658
659
660if __name__ == "__main__":
661 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
662 sys.stdout.reconfigure(errors="replace")
663 except (AttributeError, ValueError, OSError):
664 pass
665 sys.exit(main())
diff --git a/tools/bvh_rehydrate.py b/tools/bvh_rehydrate.py
new file mode 100644
index 000000000..9210a6de1
--- /dev/null
+++ b/tools/bvh_rehydrate.py
@@ -0,0 +1,480 @@
1"""Rehydrate a dehydrated XDXR BVH4 bottom-level acceleration structure on the CPU.
2
3The `*_bvh4.rpf` packs hold offline-built BLASes in the builder's dehydrated form: the header and the box
4hierarchy are there, but the leaves name primitives instead of holding vertices, and most box bounds are left
5to be recomputed. `XboxBvhBuilder.dll` turns such a buffer back into the runtime XDXR layout (docs/bvh.md §3.1)
6with its geometry. This tool does the same on the CPU, following the packing recorded in docs/bvh.md §4a, so a
7rehydrated structure can be produced without the DLL and the builder's own rehydration programs can be checked
8against it on a GPU. Standard library only; nothing is read from the package.
9
10Input layout. The buffer starts at the 64-byte header (pass --header-offset 256 for a whole `bvh4` stream, whose
11header sits at payload 0x100). Every offset in the header counts from the header. The output is the rehydrated
12structure only, `64 * (totalSizeIn64BNodes + 1)` bytes from the header on.
13
14What is done, in order (docs/bvh.md §4a):
15
16* Header. The header is copied together with the bytes after it that the builder keeps: up to `offsetToParents`
17 when the word at +0x2c is non-zero, else `16 * (9 * k * k + 4)` bytes with `k = flags >> 20 & 15`, rounded up to
18 16. The dehydrated flag (0x01000000) is cleared and the root's parent entry is set to 0xffffffff.
19* Leaves. `numElements` leaves sit at `offsetToElements` in chunks of 2,048 every 128 KiB. A chunk of `c` leaves is
20 five arrays: geometry index (3 bytes each), flags (1), base primitive (3), second primitive (3; 0xffffff = none)
21 and a vertex-order byte (1). Each leaf becomes a 64-byte `Leaf`: the base triangle's three vertices in the slots
22 the vertex-order byte selects, a fourth vertex for a second primitive (NaN when there is none), then
23 `geometryIndex << 8 | flags`, the two primitive indices and the remap word.
24* Boxes. The level table at the end of the input (last word: level count, before it one (BOX32 end, BOX16 end)
25 pair per level, offsets from `offsetToNodes`) lists the levels bottom-up. In each level the BOX32 nodes come
26 first, in groups of up to 64 per 8 KiB, then the BOX16 nodes, 64 per 4 KiB. A group starts with one word per node
27 (`children << 24 | 24-bit override mask`), then all the child pointers, then one stored value per mask bit
28 (float for BOX32, half for BOX16). A slot's box is the bounds of the already rehydrated child; the stored values
29 replace the masked components (bit `6 * slot + c`, min xyz then max xyz). BOX16 rounds min down and max up and
30 overflows to +-inf. Each node writes itself as the parent of its box children (and of TRI0 leaves when the
31 structure is updatable, flag 0x00040000).
32* Leaf frame. Vertices are mapped `(R * v - t) * s` per `compressionParams` (+0x3c): bit 31 turns on the scale
33 `2^(e - 127)` with `e` the bytes 0, 1, 2; bit 30 the translation, the centre of `sceneBounds` on an axis whose
34 bounds do not straddle zero; bits 24-29 pick one of 64 rotations in steps of pi/8 about x, y and z. The value
35 0x007f7f7f means none of it. Only rotation index 0 occurs in the measured samples.
36
37Float arithmetic is rounded to float32 after every operation, as the GPU does, so the output is meant to be
38byte-exact. Geometry is float3 vertices (any stride) with uint32, uint16 or no indices, plus an optional 3x4
39geometry transform (the instance descriptor's matrix at +0x50, docs/bvh.md §3.2), applied as `x' = M * x`.
40
41Usage:
42 python -I tools/bvh_rehydrate.py <dehydrated.bin> --geom VB[,IB] [--geom VB[,IB] ...] --out <rehydrated.bin>
43 [--header-offset N] [--stride BYTES] [--index16] [--transform 12 floats]
44 [--compare <reference.bin>]
45
46One --geom per geometry index, in order: VB is a file of vertices (three float32 at the start of each --stride
47record, default 12), IB a file of uint32 (or, with --index16, uint16) triangle indices; without IB the vertices are
48a triangle list. --transform takes the 3x4 row-major matrix as 12 comma-separated floats and applies to every
49geometry. --compare prints how many bytes differ from a reference structure. Exit status 0 on success, 2 on an
50input error.
51"""
52import argparse
53import math
54import struct
55import sys
56
57FLAG_DEHYDRATED = 0x01000000
58FLAG_UPDATABLE = 0x00040000
59NO_TRANSFORM = 0x007F7F7F
60INVALID = 0xFFFFFFFF
61TRI0, TRI1, BOX16, BOX32 = 0, 1, 4, 5
62FLT_MAX = struct.unpack("<f", b"\xff\xff\x7f\x7f")[0]
63HALF_POS_INF, HALF_NEG_INF = 0x7C00, 0xFC00
64HALF_MIN_NORMAL = 2.0 ** -14
65NAN32 = struct.unpack("<f", struct.pack("<I", 0x7FC00000))[0]
66LEAVES_PER_CHUNK, CHUNK_STRIDE = 2048, 1 << 17
67GROUP = 64
68SLOT_OF_ORDER = (2, 0, 1) # vertex-order value -> leaf vertex slot
69M32 = 0xFFFFFFFF
70
71
72# --- float32 / half helpers -------------------------------------------------------------------------------------
73
74def f32(x):
75 return struct.unpack("<f", struct.pack("<f", x))[0]
76
77
78def bits32(x):
79 return struct.unpack("<I", struct.pack("<f", x))[0]
80
81
82def from_bits32(b):
83 return struct.unpack("<f", struct.pack("<I", b & M32))[0]
84
85
86def half_to_float(h):
87 return struct.unpack("<e", struct.pack("<H", h & 0xFFFF))[0]
88
89
90def float_to_half(x):
91 try:
92 return struct.unpack("<H", struct.pack("<e", x))[0]
93 except OverflowError:
94 return HALF_NEG_INF if x < 0 else HALF_POS_INF
95
96
97def min_num(a, b):
98 """IEEE minNum: a NaN operand loses."""
99 if a != a:
100 return b
101 if b != b:
102 return a
103 return a if a <= b else b
104
105
106def max_num(a, b):
107 if a != a:
108 return b
109 if b != b:
110 return a
111 return a if a >= b else b
112
113
114def half_down(x):
115 """Largest half not above x (a box16 minimum)."""
116 if x != x:
117 return float_to_half(x)
118 b = bits32(x)
119 if x < 0.0:
120 y = min_num(from_bits32((b + 0x1FFF) & ~0x1FFF), -HALF_MIN_NORMAL)
121 else:
122 y = from_bits32(b & ~0x1FFF)
123 y = 0.0 if y < HALF_MIN_NORMAL else y
124 return float_to_half(y)
125
126
127def half_up(x):
128 """Smallest half not below x (a box16 maximum)."""
129 if x != x:
130 return float_to_half(x)
131 b = bits32(x)
132 if x > 0.0:
133 y = max_num(from_bits32((b + 0x1FFF) & ~0x1FFF), HALF_MIN_NORMAL)
134 else:
135 y = from_bits32(b & ~0x1FFF)
136 y = 0.0 if y > -HALF_MIN_NORMAL else y
137 return float_to_half(y)
138
139
140# --- header and frames ------------------------------------------------------------------------------------------
141
142class Header:
143 """The XboxBvh4Header fields this tool needs (docs/bvh.md §3.1); offsets are from the header."""
144
145 def __init__(self, buf, at=0):
146 if at < 0 or at + 64 > len(buf):
147 raise ValueError("no 64-byte header at offset %d" % at)
148 (self.flags, self.size_units, self.crc32, self.num_elements) = struct.unpack_from("<4I", buf, at)
149 self.bounds = struct.unpack_from("<6f", buf, at + 16)
150 (self.offset_to_nodes, self.prim_remap_word, self.root, self.offset_to_elements, self.offset_to_parents,
151 self.compression) = struct.unpack_from("<6I", buf, at + 40)
152
153 @property
154 def total_bytes(self):
155 return (self.size_units + 1) * 64
156
157 def kept_header_bytes(self):
158 if self.prim_remap_word:
159 n = self.offset_to_parents
160 else:
161 k = (self.flags >> 20) & 15
162 n = 16 * (9 * k * k + 4)
163 return (n + 15) & ~15
164
165 def parent_entry(self, node_offset):
166 """Address of the parent-table entry for the node at node_offset (all arithmetic is 32-bit)."""
167 unit = ((node_offset - self.offset_to_elements) & M32) >> 6
168 return (self.offset_to_parents + 4 * unit) & M32
169
170
171def rotation(index):
172 """Rotation index -> 3x3 matrix Rz * Ry * Rx, each angle a multiple of pi/8, products rounded to float32."""
173 c = (1.0, math.cos(math.pi / 8), math.cos(math.pi / 4), math.cos(3 * math.pi / 8), 0.0)
174 ix, iy, iz = index & 3, (index >> 2) & 3, (index >> 4) & 3
175 cx, sx, cy, sy, cz, sz = (f32(c[ix]), f32(c[4 - ix]), f32(c[iy]), f32(c[4 - iy]), f32(c[iz]), f32(c[4 - iz]))
176 rx = ((1.0, 0.0, 0.0), (0.0, cx, sx), (0.0, -sx, cx))
177 ry = ((cy, 0.0, -sy), (0.0, 1.0, 0.0), (sy, 0.0, cy))
178 rz = ((cz, sz, 0.0), (-sz, cz, 0.0), (0.0, 0.0, 1.0))
179
180 def mul(a, b):
181 out = []
182 for r in range(3):
183 row = []
184 for col in range(3):
185 acc = 0.0
186 for m in range(3):
187 acc = f32(acc + f32(a[r][m] * b[m][col]))
188 row.append(acc)
189 out.append(tuple(row))
190 return tuple(out)
191
192 return mul(rz, mul(ry, rx))
193
194
195class LeafFrame:
196 """The compressionParams mapping (R * v - t) * s, or the identity."""
197
198 def __init__(self, hdr):
199 word = hdr.compression
200 self.on = word != NO_TRANSFORM
201 self.r = rotation((word >> 24) & 0x3F)
202 self.t = [0.0, 0.0, 0.0]
203 self.s = [1.0, 1.0, 1.0]
204 if word >> 30 & 1:
205 for a in range(3):
206 lo, hi = hdr.bounds[a], hdr.bounds[a + 3]
207 if lo > 0.0 or hi < 0.0:
208 self.t[a] = f32(f32(lo + hi) * 0.5)
209 if word >> 31 & 1:
210 self.s = [from_bits32(((word >> (8 * a)) & 0xFF) << 23) for a in range(3)]
211
212 def apply(self, v):
213 if not self.on:
214 return v
215 out = []
216 for row in range(3):
217 acc = f32(self.r[row][0] * v[0])
218 acc = f32(self.r[row][1] * v[1] + acc)
219 acc = f32(self.r[row][2] * v[2] + acc)
220 out.append(f32(f32(acc - self.t[row]) * self.s[row]))
221 return tuple(out)
222
223
224# --- geometry ---------------------------------------------------------------------------------------------------
225
226class Geometry:
227 """float3 vertices (the first 12 bytes of each `stride` record) with optional uint32/uint16 triangle indices and
228 an optional 3x4 row-major transform applied as x' = M * x."""
229
230 def __init__(self, vertices, stride=12, indices=None, index16=False, transform=None):
231 if stride < 12:
232 raise ValueError("vertex stride %d is below 12" % stride)
233 self.vertices, self.stride, self.indices, self.index16 = bytes(vertices), stride, indices, index16
234 self.transform = transform
235
236 def triangle(self, prim):
237 if self.indices is None:
238 return 3 * prim, 3 * prim + 1, 3 * prim + 2
239 if self.index16:
240 return struct.unpack_from("<3H", self.indices, 6 * prim)
241 return struct.unpack_from("<3I", self.indices, 12 * prim)
242
243 def vertex(self, i):
244 v = struct.unpack_from("<3f", self.vertices, i * self.stride)
245 m = self.transform
246 if m is None:
247 return v
248 out = []
249 for row in range(3):
250 acc = f32(m[row][0] * v[0])
251 acc = f32(m[row][1] * v[1] + acc)
252 acc = f32(m[row][2] * v[2] + acc)
253 out.append(f32(acc + m[row][3]))
254 return tuple(out)
255
256
257# --- rehydration ------------------------------------------------------------------------------------------------
258
259def read_u24(buf, at):
260 return buf[at] | buf[at + 1] << 8 | buf[at + 2] << 16
261
262
263def leaf_records(src, hdr):
264 """Yield (leaf output offset, geometry, flags, prim0, prim1 or None, vertex order) for every leaf."""
265 remaining, chunk = hdr.num_elements, 0
266 while remaining > 0:
267 c = min(LEAVES_PER_CHUNK, remaining)
268 base = hdr.offset_to_elements + chunk * CHUNK_STRIDE
269 if base + 11 * c > len(src):
270 raise ValueError("leaf chunk %d runs past the input" % chunk)
271 for i in range(c):
272 prim1 = read_u24(src, base + 7 * c + 3 * i)
273 yield (base + 64 * i, read_u24(src, base + 3 * i), src[base + 3 * c + i], read_u24(src, base + 4 * c + 3 * i),
274 None if prim1 == 0xFFFFFF else prim1, src[base + 10 * c + i])
275 remaining -= c
276 chunk += 1
277
278
279def write_leaves(src, dst, hdr, geometries, frame):
280 for out, gi, flags, prim0, prim1, order in leaf_records(src, hdr):
281 if gi >= len(geometries):
282 raise ValueError("a leaf uses geometry index %d but %d geometries were given" % (gi, len(geometries)))
283 g = geometries[gi]
284 tri = [frame.apply(g.vertex(i)) for i in g.triangle(prim0)]
285 if prim1 is None:
286 fourth = (NAN32, NAN32, NAN32)
287 else:
288 j = g.triangle(prim1)
289 fourth = frame.apply(g.vertex(j[0] if order & 0x20 else j[1] if order & 0x80 else j[2]))
290 a, b = order & 3, (order >> 2) & 3
291 slots = [None, None, None, fourth]
292 for which, value in zip((a, b, (a ^ 3) - b), tri):
293 slots[SLOT_OF_ORDER[which]] = value
294 struct.pack_into("<12f4I", dst, out, *slots[0], *slots[1], *slots[2], *slots[3],
295 (gi << 8 | flags) & M32, prim0, INVALID if prim1 is None else prim1,
296 (order & 0xF) | ((order << 4) & 0xF00))
297
298
299def node_bounds(dst, ptr):
300 """(min xyz, max xyz) of the rehydrated node a child pointer names."""
301 kind, at = ptr & 7, (ptr >> 3) << 6
302 if kind == TRI0:
303 v = struct.unpack_from("<12f", dst, at)
304 pts = [v[0:3], v[3:6], v[6:9]] + ([v[9:12]] if struct.unpack_from("<I", dst, at + 48)[0] & 0x80 else [])
305 elif kind == TRI1:
306 v = struct.unpack_from("<9f", dst, at + 12)
307 pts = [v[0:3], v[3:6], v[6:9]]
308 elif kind == BOX32:
309 f = struct.unpack_from("<24f", dst, at + 16)
310 pts = None
311 lo = [f[a] for a in range(3)]
312 hi = [f[3 + a] for a in range(3)]
313 for s in range(1, 4):
314 for a in range(3):
315 lo[a] = min_num(lo[a], f[6 * s + a])
316 hi[a] = max_num(hi[a], f[6 * s + 3 + a])
317 return tuple(lo) + tuple(hi)
318 elif kind == BOX16:
319 h = struct.unpack_from("<24H", dst, at + 16)
320 out = []
321 for c in range(6):
322 best = h[c]
323 for s in range(1, 4):
324 cand = h[6 * s + c]
325 x, y = half_to_float(best), half_to_float(cand)
326 if x != x or (y == y and ((y < x) if c < 3 else (y > x))):
327 best = cand
328 out.append(half_to_float(best))
329 return tuple(out)
330 else:
331 return (FLT_MAX,) * 3 + (-FLT_MAX,) * 3
332 lo, hi = list(pts[0]), list(pts[0])
333 for p in pts[1:]:
334 for a in range(3):
335 lo[a] = min_num(lo[a], p[a])
336 hi[a] = max_num(hi[a], p[a])
337 return tuple(lo) + tuple(hi)
338
339
340def levels(src, hdr):
341 """[(box32 start, box32 count, box16 start, box16 count)] bottom-up, offsets from offsetToNodes."""
342 end = hdr.total_bytes
343 count = struct.unpack_from("<I", src, end - 4)[0]
344 table = end - 4 - 8 * count
345 if table < 64:
346 raise ValueError("level table with %d levels does not fit" % count)
347 out, prev = [], 0
348 for lv in range(count):
349 b32, b16 = struct.unpack_from("<2I", src, table + 8 * lv)
350 if b32 < prev or b16 < b32 or (b32 - prev) % 128 or (b16 - b32) % 64:
351 raise ValueError("level %d of the level table is out of order" % lv)
352 out.append((prev, (b32 - prev) // 128, b32, (b16 - b32) // 64))
353 prev = b16
354 return out
355
356
357def write_box_groups(src, dst, hdr, start, count, wide):
358 """Rehydrate `count` BOX32 (wide) or BOX16 nodes stored from offsetToNodes + start."""
359 node_size, group_bytes = (128, 1 << 13) if wide else (64, 1 << 12)
360 for g in range((count + GROUP - 1) // GROUP):
361 n = min(GROUP, count - g * GROUP)
362 base = hdr.offset_to_nodes + start + g * group_bytes
363 words = struct.unpack_from("<%dI" % n, src, base)
364 total_children = sum(w >> 24 for w in words)
365 child_at = base + 4 * n
366 value_at = base + 4 * (n + total_children)
367 for t, word in enumerate(words):
368 kids, mask = word >> 24, word & 0xFFFFFF
369 children = list(struct.unpack_from("<%dI" % kids, src, child_at)) + [INVALID] * (4 - kids)
370 child_at += 4 * kids
371 comps = []
372 for slot in range(4):
373 if slot < kids:
374 b = node_bounds(dst, children[slot])
375 comps += list(b) if wide else [half_down(b[0]), half_down(b[1]), half_down(b[2]),
376 half_up(b[3]), half_up(b[4]), half_up(b[5])]
377 else:
378 comps += [FLT_MAX] * 3 + [-FLT_MAX] * 3 if wide else [HALF_POS_INF] * 3 + [HALF_NEG_INF] * 3
379 for bit in range(24):
380 if mask >> bit & 1:
381 if wide:
382 comps[bit] = struct.unpack_from("<f", src, value_at)[0]
383 value_at += 4
384 else:
385 comps[bit] = struct.unpack_from("<H", src, value_at)[0]
386 value_at += 2
387 at = base + t * node_size
388 if wide:
389 struct.pack_into("<4I24f4I", dst, at, *children, *comps, 0, 0, 0, 0)
390 else:
391 struct.pack_into("<4I24H", dst, at, *children, *comps)
392 me = (at >> 6) << 3 | (BOX32 if wide else BOX16)
393 for child in children:
394 if (child & 6) == 4 or ((child & 7) == TRI0 and hdr.flags & FLAG_UPDATABLE):
395 entry = hdr.parent_entry(((child >> 3) << 6) & M32)
396 if entry + 4 <= len(dst):
397 struct.pack_into("<I", dst, entry, me)
398
399
400def rehydrate(dehydrated, geometries, header_offset=0):
401 """Return the rehydrated structure (bytearray) for a dehydrated BLAS and one Geometry per geometry index."""
402 hdr = Header(dehydrated, header_offset)
403 if not hdr.flags & FLAG_DEHYDRATED:
404 raise ValueError("the dehydrated flag (0x01000000) is not set")
405 src = bytes(dehydrated[header_offset:header_offset + hdr.total_bytes])
406 if len(src) < hdr.total_bytes:
407 raise ValueError("the input is shorter than the %d bytes the header declares" % hdr.total_bytes)
408 dst = bytearray(hdr.total_bytes)
409 kept = hdr.kept_header_bytes()
410 if kept > len(src):
411 raise ValueError("the kept header bytes (%d) run past the input" % kept)
412 dst[:kept] = src[:kept]
413 struct.pack_into("<I", dst, 0, hdr.flags & ~FLAG_DEHYDRATED & M32)
414 root_entry = hdr.parent_entry(((hdr.root >> 3) << 6) & M32)
415 if root_entry + 4 <= len(dst):
416 struct.pack_into("<I", dst, root_entry, INVALID)
417 write_leaves(src, dst, hdr, list(geometries), LeafFrame(hdr))
418 if hdr.root & 7 in (BOX16, BOX32):
419 for b32_start, b32_count, b16_start, b16_count in levels(src, hdr):
420 write_box_groups(src, dst, hdr, b32_start, b32_count, True)
421 write_box_groups(src, dst, hdr, b16_start, b16_count, False)
422 return dst
423
424
425# --- command line -----------------------------------------------------------------------------------------------
426
427def parse_transform(text):
428 vals = [float(x) for x in text.split(",")]
429 if len(vals) != 12:
430 raise ValueError("--transform needs 12 comma-separated floats, got %d" % len(vals))
431 return tuple(tuple(f32(v) for v in vals[4 * r:4 * r + 4]) for r in range(3))
432
433
434def main(argv=None):
435 ap = argparse.ArgumentParser(description="Rehydrate a dehydrated XDXR BVH4 BLAS on the CPU (docs/bvh.md §4a).")
436 ap.add_argument("dehydrated")
437 ap.add_argument("--geom", action="append", default=[], metavar="VB[,IB]")
438 ap.add_argument("--out", required=True)
439 ap.add_argument("--header-offset", type=int, default=0)
440 ap.add_argument("--stride", type=int, default=12)
441 ap.add_argument("--index16", action="store_true")
442 ap.add_argument("--transform")
443 ap.add_argument("--compare")
444 a = ap.parse_args(argv)
445 try:
446 transform = parse_transform(a.transform) if a.transform else None
447 geometries = []
448 for spec in a.geom:
449 parts = spec.split(",")
450 with open(parts[0], "rb") as f:
451 vb = f.read()
452 ib = None
453 if len(parts) > 1 and parts[1]:
454 with open(parts[1], "rb") as f:
455 ib = f.read()
456 geometries.append(Geometry(vb, a.stride, ib, a.index16, transform))
457 with open(a.dehydrated, "rb") as f:
458 data = f.read()
459 out = rehydrate(data, geometries, a.header_offset)
460 except (OSError, ValueError, struct.error) as e:
461 print("error: %s" % e, file=sys.stderr)
462 return 2
463 with open(a.out, "wb") as f:
464 f.write(out)
465 print("rehydrated %d bytes, %d leaves, %d geometries -> %s" % (len(out), Header(data, a.header_offset).num_elements,
466 len(geometries), a.out))
467 if a.compare:
468 with open(a.compare, "rb") as f:
469 ref = f.read()
470 diff = sum(x != y for x, y in zip(out, ref)) + abs(len(out) - len(ref))
471 print("differs from %s in %d bytes" % (a.compare, diff))
472 return 0
473
474
475if __name__ == "__main__":
476 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
477 sys.stdout.reconfigure(errors="replace")
478 except (AttributeError, ValueError, OSError):
479 pass
480 sys.exit(main())
diff --git a/tools/content_definitions.py b/tools/content_definitions.py
new file mode 100644
index 000000000..21c0f5105
--- /dev/null
+++ b/tools/content_definitions.py
@@ -0,0 +1,226 @@
1"""Read local content-definition XML (ASSET-149), without resolving references.
2
3Accepts XML files or rpf9_carve directories. The CLI prints aggregate counts only.
4The Python API returns ordered records containing local game data: never publish
5those records. Archive offsets identify recovered spans, not named RPF entries.
6"""
7from __future__ import annotations
8
9import argparse
10from dataclasses import dataclass
11import json
12import os
13import sys
14import xml.etree.ElementTree as ET
15
16ROOTS = {
17 "CDataFileMgr__ContentChangeSetDef": "change_set",
18 "CDataFileMgr__ContentDef": "content",
19 "SSetupData": "setup",
20}
21
22
23class ContentError(ValueError):
24 """Invalid content XML; messages never include input values or paths."""
25
26
27@dataclass(frozen=True)
28class Record:
29 tag: str
30 attributes: tuple[tuple[str, str], ...]
31 text: str
32 tail: str
33 children: tuple[Record, ...]
34
35 def select(self, *path: str) -> tuple[Record, ...]:
36 """Select ordered direct-child paths; duplicates are not collapsed."""
37 nodes = (self,)
38 for tag in path:
39 nodes = tuple(child for node in nodes for child in node.children if child.tag == tag)
40 return nodes
41
42 def scalar(self, tag: str) -> str | None:
43 """One text/value field, untyped; absent is None, explicitly empty is ''."""
44 fields = self.select(tag)
45 if not fields:
46 return None
47 if len(fields) != 1 or fields[0].children:
48 raise ContentError("ambiguous scalar field")
49 field = fields[0]
50 text = field.text.strip()
51 attrs = dict(field.attributes)
52 if "value" in attrs:
53 if text:
54 raise ContentError("scalar has both text and value attribute")
55 return attrs["value"]
56 return text
57
58
59@dataclass(frozen=True)
60class FileEntry:
61 filename: str | None
62 file_type: str | None
63 record: Record
64
65
66@dataclass(frozen=True)
67class ContentDocument:
68 kind: str
69 root: Record
70
71 @property
72 def files(self) -> tuple[FileEntry, ...]:
73 if self.kind != "change_set":
74 return ()
75 return tuple(FileEntry(item.scalar("filename"), item.scalar("fileType"), item)
76 for item in self.root.select("fileList", "Item"))
77
78 @property
79 def included_changesets(self) -> tuple[Record, ...]:
80 return self.root.select("includedChangesets", "Item") if self.kind == "content" else ()
81
82 @property
83 def included_sets(self) -> tuple[Record, ...]:
84 return self.root.select("includedSets", "Item") if self.kind == "content" else ()
85
86 @property
87 def change_set_groups(self) -> tuple[Record, ...]:
88 return self.root.select("contentChangeSetGroups", "Item") if self.kind == "setup" else ()
89
90
91class _Builder(ET.TreeBuilder):
92 def __init__(self):
93 super().__init__()
94 self.depth = 0
95
96 def start(self, tag, attrs):
97 self.depth += 1
98 if self.depth > 128:
99 raise ContentError("XML nesting exceeds 128 elements")
100 return super().start(tag, attrs)
101
102 def end(self, tag):
103 self.depth -= 1
104 return super().end(tag)
105
106 def doctype(self, name, pubid, system):
107 raise ContentError("DTD declarations are unsupported")
108
109
110def parse_content(chunks, *, max_bytes: int = 64 << 20) -> ContentDocument:
111 """Parse one document from byte chunks. No partially parsed result escapes.
112
113 Preserves all elements, attributes, text and tails (after XML normalization),
114 including unknown fields. Comments/PIs are not configuration fields. This
115 reader retains a whole document, with a configurable byte limit, not a whole
116 archive. No path, macro, hash or include is resolved and no numeric conversion
117 is inferred. Namespaced roots are not silently treated as the known schema.
118 """
119 if max_bytes < 1:
120 raise ValueError("max_bytes must be positive")
121 parser = ET.XMLParser(target=_Builder())
122 total = 0
123 try:
124 for chunk in chunks:
125 if not isinstance(chunk, bytes):
126 raise TypeError("content input must contain byte chunks")
127 total += len(chunk)
128 if total > max_bytes:
129 raise ContentError("XML exceeds byte limit")
130 parser.feed(chunk)
131 element = parser.close()
132 except ContentError:
133 raise
134 except (ET.ParseError, LookupError, ValueError):
135 raise ContentError("malformed or unsupported XML") from None
136 if element.tag not in ROOTS:
137 raise ContentError("unsupported content root")
138
139 def record(el):
140 return Record(el.tag, tuple(el.attrib.items()), el.text or "", el.tail or "",
141 tuple(record(child) for child in el))
142
143 result = ContentDocument(ROOTS[element.tag], record(element))
144 # Validate the known scalar fields exposed by the file-entry convenience API.
145 result.files
146 for item in result.included_changesets:
147 item.scalar("loadPath")
148 return result
149
150
151def file_chunks(stream):
152 while chunk := stream.read(65536):
153 yield chunk
154
155
156def carve_documents(directory):
157 """Yield (offset, stored size, document) for XML payloads in an existing carve.
158
159 Existing grouping determines spans; it does not recover encrypted TOC names.
160 Strict reads prevent missing .bin files falling back to index header bytes.
161 Non-content XML yields None; malformed content raises ContentError.
162 """
163 tools_dir = os.path.dirname(os.path.abspath(__file__))
164 if tools_dir not in sys.path:
165 sys.path.insert(0, tools_dir)
166 import gamedata_index as gi
167
168 class Source(gi.DirectorySource):
169 def read(self, row):
170 ext = ".bk2" if row.get("type") == "bink2" else ".bin"
171 with open(os.path.join(self.directory, f'{row["off"]:012x}{ext}'), "rb") as stream:
172 # Grouping only needs the Bink signature, not the video payload.
173 return stream.read(64) if ext == ".bk2" else stream.read()
174
175 source = Source(directory)
176 positions = {r["off"]: i for i, r in enumerate(source.rows)}
177 for row in gi.build_rows(source.rows, source):
178 if row["type"] != "xml":
179 continue
180 if row["root"] not in ROOTS:
181 yield row["offset"], row["stored"], None
182 continue
183 first = positions[row["offset"]]
184 group = source.rows[first:first + row["chunks"]]
185 yield row["offset"], row["stored"], parse_content(source.read(r) for r in group)
186
187
188def main() -> int:
189 cli = argparse.ArgumentParser(description=__doc__)
190 cli.add_argument("inputs", nargs="+", help="local XML files or carve directories")
191 args = cli.parse_args()
192 counts = dict(documents=0, change_sets=0, contents=0, setups=0, files=0,
193 included_changesets=0, included_sets=0, groups=0,
194 other_xml=0, failed_inputs=0)
195
196 def add(doc):
197 if doc is None:
198 counts["other_xml"] += 1
199 return
200 counts["documents"] += 1
201 counts[{"change_set": "change_sets", "content": "contents", "setup": "setups"}[doc.kind]] += 1
202 counts["files"] += len(doc.files)
203 counts["included_changesets"] += len(doc.included_changesets)
204 counts["included_sets"] += len(doc.included_sets)
205 counts["groups"] += len(doc.change_set_groups)
206
207 for path in args.inputs:
208 try:
209 if os.path.isdir(path):
210 for _, _, doc in carve_documents(path):
211 add(doc)
212 else:
213 with open(path, "rb") as stream:
214 add(parse_content(file_chunks(stream)))
215 except (OSError, ContentError, ValueError, KeyError, TypeError):
216 counts["failed_inputs"] += 1
217 print(json.dumps(counts, sort_keys=True))
218 return int(bool(counts["failed_inputs"]))
219
220
221if __name__ == "__main__":
222 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
223 sys.stdout.reconfigure(errors="replace")
224 except (AttributeError, ValueError, OSError):
225 pass
226 raise SystemExit(main())
diff --git a/tools/cpu_ref.py b/tools/cpu_ref.py
index 1a89b2766..694782f52 100644
--- a/tools/cpu_ref.py
+++ b/tools/cpu_ref.py
@@ -392,9 +392,9 @@ class Machine:
392 else: 392 else:
393 raise Unsupported(arg.get("t", kind), self.pc, "operand kind is not modelled") 393 raise Unsupported(arg.get("t", kind), self.pc, "operand kind is not modelled")
394 if arg.get("abs"): 394 if arg.get("abs"):
395 value = abs(value - (1 << 32)) if value & SIGN32 else value 395 value &= 0x7FFFFFFF
396 if arg.get("neg"): 396 if arg.get("neg"):
397 value = (-value) & MASK32 397 value ^= SIGN32
398 return value & MASK32 398 return value & MASK32
399 399
400 def _float_src(self, arg, lane): 400 def _float_src(self, arg, lane):
diff --git a/tools/d16_format_probe.py b/tools/d16_format_probe.py
index 23fe49b6c..b8ed5e838 100644
--- a/tools/d16_format_probe.py
+++ b/tools/d16_format_probe.py
@@ -268,6 +268,18 @@ def self_test():
268 return 0 268 return 0
269 269
270 270
271def write_report(path, doc):
272 """Write the JSON report, creating its folder; one ERROR line instead of a traceback on failure."""
273 try:
274 os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
275 with open(path, "w", encoding="utf-8", newline="\n") as f:
276 json.dump(doc, f, indent=1)
277 except OSError as e:
278 print(f"ERROR: cannot write {path}: {e}", file=sys.stderr)
279 return False
280 return True
281
282
271def main(argv=None): 283def main(argv=None):
272 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) 284 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
273 ap.add_argument("--formats", default=",".join(FORMATS)) 285 ap.add_argument("--formats", default=",".join(FORMATS))
@@ -283,6 +295,8 @@ def main(argv=None):
283 bad = [f for f in fmts if f not in FORMATS] + [w for w in a.waves.split(",") if w and w not in ("32", "64")] 295 bad = [f for f in fmts if f not in FORMATS] + [w for w in a.waves.split(",") if w and w not in ("32", "64")]
284 if bad or not fmts or not waves: 296 if bad or not fmts or not waves:
285 ap.error("unknown or empty: " + ", ".join(bad or ["--formats/--waves"])) 297 ap.error("unknown or empty: " + ", ".join(bad or ["--formats/--waves"]))
298 if a.json and os.path.isdir(a.json):
299 ap.error(f"--json {a.json} is a folder, not a file")
286 from hw_oracle import asm, runner 300 from hw_oracle import asm, runner
287 try: 301 try:
288 oracle = runner.open_oracle(arch=a.hw_arch) 302 oracle = runner.open_oracle(arch=a.hw_arch)
@@ -327,9 +341,8 @@ def main(argv=None):
327 return 2 341 return 2
328 finally: 342 finally:
329 oracle.close() 343 oracle.close()
330 if a.json: 344 if a.json and not write_report(a.json, report):
331 with open(a.json, "w", encoding="utf-8", newline="\n") as f: 345 return 2
332 json.dump(report, f, indent=1)
333 return rc 346 return rc
334 347
335 348
diff --git a/tools/dds_png.py b/tools/dds_png.py
index a19d3e870..7bf5ba7bd 100644
--- a/tools/dds_png.py
+++ b/tools/dds_png.py
@@ -7,6 +7,8 @@ block-compressed formats (BC1, BC2, BC3, BC4, BC5, BC7).
7BC7 covers all eight modes. DXGI 97/98/99 (typeless, UNORM, UNORM_SRGB) emit 7BC7 covers all eight modes. DXGI 97/98/99 (typeless, UNORM, UNORM_SRGB) emit
8the stored RGBA8 values with no sRGB transfer, and the reserved mode (no mode 8the stored RGBA8 values with no sRGB transfer, and the reserved mode (no mode
9bit in the first byte) decodes as transparent black. BC6H is not supported. 9bit in the first byte) decodes as transparent black. BC6H is not supported.
10DX10 premultiplied alpha is converted to straight alpha for PNG; sRGB colors are
11unpremultiplied in linear light and returned in their sRGB encoding.
10 12
11Usage: 13Usage:
12 python -I tools/dds_png.py <in.dds> <out.png> [--max-size N] 14 python -I tools/dds_png.py <in.dds> <out.png> [--max-size N]
@@ -30,6 +32,7 @@ DDS_HEADER_SIZE = 128
30DDS_DX10_HEADER_SIZE = 148 32DDS_DX10_HEADER_SIZE = 148
31DDSD_PITCH = 0x8 33DDSD_PITCH = 0x8
32DDS_ALPHA_MODE_MASK = 0x7 34DDS_ALPHA_MODE_MASK = 0x7
35DDS_ALPHA_MODE_PREMULTIPLIED = 2
33DDS_ALPHA_MODE_OPAQUE = 3 36DDS_ALPHA_MODE_OPAQUE = 3
34 37
35DDPF_ALPHAPIXELS = 0x1 38DDPF_ALPHAPIXELS = 0x1
@@ -51,11 +54,15 @@ _FOURCC_MAP: dict[bytes, str] = {
51} 54}
52 55
53_DXGI_MAP: dict[int, str] = { 56_DXGI_MAP: dict[int, str] = {
57 # Typeless byte formats use the same channel layout as their UNORM variants.
58 27: "RGBA8",
54 28: "RGBA8", 59 28: "RGBA8",
55 29: "RGBA8", 60 29: "RGBA8",
56 87: "BGRA8", 61 87: "BGRA8",
62 90: "BGRA8",
57 91: "BGRA8", 63 91: "BGRA8",
58 88: "BGRX8", 64 88: "BGRX8",
65 92: "BGRX8",
59 93: "BGRX8", 66 93: "BGRX8",
60 70: "BC1", 67 70: "BC1",
61 71: "BC1", 68 71: "BC1",
@@ -77,6 +84,12 @@ _DXGI_MAP: dict[int, str] = {
77 99: "BC7", 84 99: "BC7",
78} 85}
79 86
87_SRGB_DXGI_FORMATS = frozenset((29, 72, 75, 78, 91, 93, 99))
88_SRGB_TO_LINEAR = tuple(
89 x / 12.92 if x <= 0.04045 else ((x + 0.055) / 1.055) ** 2.4
90 for x in (v / 255.0 for v in range(256))
91)
92
80_CANONICAL_MASKS: dict[tuple[int, int, int, int], str] = { 93_CANONICAL_MASKS: dict[tuple[int, int, int, int], str] = {
81 (0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000): "BGRA8", 94 (0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000): "BGRA8",
82 (0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000): "BGRX8", 95 (0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000): "BGRX8",
@@ -881,8 +894,27 @@ def _decode_bc7(data: bytes | bytearray | memoryview, offset: int, width: int, h
881 return bytes(out) 894 return bytes(out)
882 895
883 896
897def _unpremultiply_rgba(rgba: bytes, srgb: bool) -> bytes:
898 """Straight RGBA8, rounding color channels to the nearest byte and keeping alpha unchanged."""
899 out = bytearray(rgba)
900 for p in range(0, len(out), 4):
901 alpha = rgba[p + 3]
902 if alpha == 0:
903 out[p:p + 3] = b"\x00\x00\x00"
904 elif alpha < 255:
905 for c in range(p, p + 3):
906 if srgb:
907 linear = min(1.0, _SRGB_TO_LINEAR[rgba[c]] * 255.0 / alpha)
908 encoded = (12.92 * linear if linear <= 0.0031308
909 else 1.055 * linear ** (1.0 / 2.4) - 0.055)
910 out[c] = min(255, int(encoded * 255.0 + 0.5))
911 else:
912 out[c] = min(255, (rgba[c] * 255 + alpha // 2) // alpha)
913 return bytes(out)
914
915
884def decode_dds(data: bytes) -> tuple[int, int, bytes]: 916def decode_dds(data: bytes) -> tuple[int, int, bytes]:
885 """Decode mip 0 of a DDS buffer into top-down row-major RGBA8 bytes.""" 917 """Decode mip 0 into top-down row-major RGBA8, with straight alpha for premultiplied DX10 images."""
886 info, masks = _parse_header_internal(data) 918 info, masks = _parse_header_internal(data)
887 width = int(info["width"]) # type: ignore[arg-type] 919 width = int(info["width"]) # type: ignore[arg-type]
888 height = int(info["height"]) # type: ignore[arg-type] 920 height = int(info["height"]) # type: ignore[arg-type]
@@ -914,7 +946,10 @@ def decode_dds(data: bytes) -> tuple[int, int, bytes]:
914 946
915 if offset == DDS_DX10_HEADER_SIZE: 947 if offset == DDS_DX10_HEADER_SIZE:
916 misc_flags2 = struct.unpack_from("<I", data, 144)[0] 948 misc_flags2 = struct.unpack_from("<I", data, 144)[0]
917 if misc_flags2 & DDS_ALPHA_MODE_MASK == DDS_ALPHA_MODE_OPAQUE: 949 alpha_mode = misc_flags2 & DDS_ALPHA_MODE_MASK
950 if alpha_mode == DDS_ALPHA_MODE_PREMULTIPLIED:
951 rgba = _unpremultiply_rgba(rgba, info["dxgi_format"] in _SRGB_DXGI_FORMATS)
952 elif alpha_mode == DDS_ALPHA_MODE_OPAQUE:
918 opaque = bytearray(rgba) 953 opaque = bytearray(rgba)
919 opaque[3::4] = b"\xff" * (width * height) 954 opaque[3::4] = b"\xff" * (width * height)
920 rgba = bytes(opaque) 955 rgba = bytes(opaque)
diff --git a/tools/ds_permute_probe.py b/tools/ds_permute_probe.py
new file mode 100644
index 000000000..98ef361d8
--- /dev/null
+++ b/tools/ds_permute_probe.py
@@ -0,0 +1,193 @@
1r"""Measure RDNA2 (GFX10) `ds_permute_b32` natively via `tools/hw_oracle` (SHADER-133).
2
3Covers collisions (2-way, 4-way, 32-way, and with the highest lane masked off in EXEC), unaddressed active
4destination lanes, EXEC off on source and destination, `offset:` addition and low-bit carry (`((vAddr + offset)
5>> 2) mod 32`), wave64 independent 32-lane halves, and partial waves (20 threads in wave32, 40 in wave64).
6
7Usage:
8 python -I tools/ds_permute_probe.py [--waves 32,64] [--json out.json]
9 python -I tools/ds_permute_probe.py --self-test # pure-Python model checks, no GPU
10
11Exit 0 when every case matches the RDNA2 model (or --self-test passed), 1 on a mismatch, 2 on a harness error,
1277 when tools/hw_oracle is unavailable or the GPU is not GFX10. Standard library only; nothing here reads game
13files.
14"""
15import argparse
16import json
17import os
18import sys
19
20HERE = os.path.dirname(os.path.abspath(__file__))
21sys.dont_write_bytecode = True
22if HERE not in sys.path:
23 sys.path.insert(0, HERE)
24
25SENTINEL = 0xCAFE0000
26PAYLOAD_BASE = 0x1000
27
28
29def model_ds_permute(wave, addrs, exec_mask, offset=0, threads=None):
30 """RDNA2 hardware model for ds_permute_b32 (wave32 or wave64).
31
32 Wave64 runs as two independent 32-lane halves. Within each half:
33 - active source lane i sends (PAYLOAD_BASE + lane) to target ((addrs[lane] + offset) >> 2) % 32
34 - on a collision, the highest-numbered active lane in the half wins
35 - unaddressed active destination lanes receive 0
36 - inactive destination lanes keep SENTINEL | lane
37 - lanes >= threads do not execute (initial EXEC bit is 0)
38 """
39 if threads is None:
40 threads = wave
41 live_mask = ((1 << threads) - 1) & exec_mask
42 out = [SENTINEL | l for l in range(wave)]
43 for base in range(0, wave, 32):
44 tmp = [0] * 32
45 for i in range(32):
46 lane = base + i
47 if (live_mask >> lane) & 1:
48 dst = ((addrs[lane] + offset) >> 2) & 31
49 tmp[dst] = PAYLOAD_BASE + lane
50 for i in range(32):
51 lane = base + i
52 if (live_mask >> lane) & 1:
53 out[lane] = tmp[i]
54 return out
55
56
57def _make_kernel(asm_mod, body_lines, wave, threads=None):
58 if threads is None:
59 threads = wave
60 restore = "s_mov_b32 exec_lo, 0xffffffff" if wave == 32 else "s_mov_b64 exec, -1"
61 lines = [
62 f"v_or_b32 v10, 0x{SENTINEL:x}, v0",
63 f"v_add_nc_u32 v2, 0x{PAYLOAD_BASE:x}, v0",
64 ] + body_lines + [
65 restore,
66 "v_lshlrev_b32 v11, 2, v0",
67 "global_store_b32 v11, v10, s[2:3]",
68 "s_waitcnt_vscnt null, 0x0",
69 "s_endpgm",
70 ]
71 return asm_mod.Kernel(lines, wave, threads, wave, raw=True, vgprs=16, sgprs=16)
72
73
74def build_cases(wave):
75 """List of (name, body_lines, addrs, exec_mask, offset, threads) for wave32 or wave64."""
76 full_mask = (1 << wave) - 1
77 mask_no_lo8 = 0xFFFFFF00 if wave == 32 else ((0xFFFFFF00 << 32) | 0xFFFFFF00)
78 mask_no_top = 0x7FFFFFFF if wave == 32 else ((0x7FFFFFFF << 32) | 0x7FFFFFFF)
79 exec_no_lo8 = (["s_mov_b32 exec_lo, 0xffffff00"] if wave == 32
80 else ["s_mov_b32 exec_lo, 0xffffff00", "s_mov_b32 exec_hi, 0xffffff00"])
81 exec_no_top = (["s_mov_b32 exec_lo, 0x7fffffff"] if wave == 32
82 else ["s_mov_b32 exec_lo, 0x7fffffff", "s_mov_b32 exec_hi, 0x7fffffff"])
83 part_threads = 20 if wave == 32 else 40
84 return [
85 ("rot_plus1_offset4_lowbits",
86 ["v_lshlrev_b32 v3, 2, v0", "v_and_b32 v4, 3, v0", "v_or_b32 v3, v3, v4",
87 "ds_permute_b32 v10, v3, v2 offset:4", "s_waitcnt lgkmcnt(0)"],
88 [(l << 2) | (l & 3) for l in range(wave)], full_mask, 4, wave),
89 ("offset_lowbit_carry",
90 ["v_mov_b32 v3, 3", "ds_permute_b32 v10, v3, v2 offset:1", "s_waitcnt lgkmcnt(0)"],
91 [3] * wave, full_mask, 1, wave),
92 ("unaddressed_odd_and_2way_collision",
93 ["v_and_b32 v3, 0xfffffffe, v0", "v_lshlrev_b32 v3, 2, v3",
94 "ds_permute_b32 v10, v3, v2", "s_waitcnt lgkmcnt(0)"],
95 [(l & ~1) << 2 for l in range(wave)], full_mask, 0, wave),
96 ("collision_4way",
97 ["v_and_b32 v3, 0xfffffffc, v0", "v_lshlrev_b32 v3, 2, v3",
98 "ds_permute_b32 v10, v3, v2", "s_waitcnt lgkmcnt(0)"],
99 [(l & ~3) << 2 for l in range(wave)], full_mask, 0, wave),
100 ("collision_all_to_0",
101 ["v_mov_b32 v3, 0", "ds_permute_b32 v10, v3, v2", "s_waitcnt lgkmcnt(0)"],
102 [0] * wave, full_mask, 0, wave),
103 ("collision_all_to_0_top_off",
104 exec_no_top + ["v_mov_b32 v3, 0", "ds_permute_b32 v10, v3, v2", "s_waitcnt lgkmcnt(0)"],
105 [0] * wave, mask_no_top, 0, wave),
106 ("exec_off_src_and_dst",
107 exec_no_lo8 + ["v_lshlrev_b32 v3, 2, v0", "ds_permute_b32 v10, v3, v2 offset:4", "s_waitcnt lgkmcnt(0)"],
108 [l << 2 for l in range(wave)], mask_no_lo8, 4, wave),
109 ("addr_plus32_wrap_halves",
110 ["v_add_nc_u32 v3, 32, v0", "v_lshlrev_b32 v3, 2, v3",
111 "ds_permute_b32 v10, v3, v2", "s_waitcnt lgkmcnt(0)"],
112 [(l + 32) << 2 for l in range(wave)], full_mask, 0, wave),
113 ("partial_wave",
114 ["v_lshlrev_b32 v3, 2, v0", "ds_permute_b32 v10, v3, v2 offset:4", "s_waitcnt lgkmcnt(0)"],
115 [l << 2 for l in range(wave)], full_mask, 4, part_threads),
116 ]
117
118
119def probe_wave(oracle, asm_mod, wave):
120 cases = build_cases(wave)
121 kernels = [_make_kernel(asm_mod, body, wave, threads) for _, body, _, _, _, threads in cases]
122 results = oracle.run(kernels, words=wave)
123 report = {}
124 ok = 0
125 for (name, _, addrs, exec_mask, offset, threads), got in zip(cases, results):
126 if isinstance(got, str) or len(got) < threads:
127 raise RuntimeError(f"{name} wave{wave}: {got}")
128 want = model_ds_permute(wave, addrs, exec_mask, offset, threads)
129 # Only check running lanes 0..threads-1 (lanes >= threads did not execute global_store_b32).
130 diffs = [{"lane": i, "hw": f"{got[i]:#x}", "want": f"{want[i]:#x}"}
131 for i in range(threads) if got[i] != want[i]]
132 if not diffs:
133 ok += 1
134 report[name] = {"lanes_checked": threads, "mismatches": len(diffs), "first_diffs": diffs[:4]}
135 return {"cases_total": len(cases), "cases_ok": ok, "cases": report}
136
137
138def self_test():
139 # Wave32: all-to-0 collision -> highest lane 31 wins; lane 1..31 unaddressed -> 0
140 w32 = model_ds_permute(32, [0] * 32, 0xFFFFFFFF)
141 assert w32[0] == PAYLOAD_BASE + 31 and all(w == 0 for w in w32[1:])
142 # Wave64: two independent halves, +32 wrap keeps each lane in its own half
143 w64 = model_ds_permute(64, [(l + 32) << 2 for l in range(64)], (1 << 64) - 1)
144 assert w64 == [PAYLOAD_BASE + l for l in range(64)]
145 # EXEC off on destination keeps SENTINEL|lane, off source leaves target 0
146 w32_e = model_ds_permute(32, [l << 2 for l in range(32)], 0xFFFFFF00, offset=4)
147 assert w32_e[0] == (SENTINEL | 0) and w32_e[8] == 0 and w32_e[9] == PAYLOAD_BASE + 8
148 # Low-bit carry: (3 + 1) >> 2 == 1
149 w32_c = model_ds_permute(32, [3] * 32, 0xFFFFFFFF, offset=1)
150 assert w32_c[1] == PAYLOAD_BASE + 31 and w32_c[0] == 0
151 # Partial wave64 (40 threads): low half wraps, high half lane 32 gets 0
152 w64_p = model_ds_permute(64, [l << 2 for l in range(64)], (1 << 64) - 1, offset=4, threads=40)
153 assert w64_p[0] == PAYLOAD_BASE + 31 and w64_p[32] == 0 and w64_p[33] == PAYLOAD_BASE + 32
154 print("self-test OK")
155
156
157def main():
158 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
159 ap.add_argument("--waves", default="32,64", help="wave sizes to run (default: 32,64)")
160 ap.add_argument("--json", dest="json_out", help="write full JSON report to this path")
161 ap.add_argument("--self-test", action="store_true", help="check the Python model without a GPU")
162 args = ap.parse_args()
163 if args.self_test:
164 self_test()
165 return 0
166 from hw_oracle import asm, runner
167 try:
168 oracle = runner.open_oracle()
169 except runner.Unavailable as exc:
170 print(f"SKIP: {exc}", file=sys.stderr)
171 return 77
172 if asm.family(oracle.arch) != "gfx10":
173 print(f"SKIP: {oracle.arch} is not GFX10 (RDNA1/RDNA2)", file=sys.stderr)
174 return 77
175 waves = [int(w) for w in args.waves.split(",") if w.strip()]
176 out = {"arch": oracle.arch, "waves": {}}
177 mismatches = 0
178 for wave in waves:
179 res = probe_wave(oracle, asm, wave)
180 out["waves"][str(wave)] = res
181 if res["cases_ok"] != res["cases_total"]:
182 mismatches += 1
183 print(f"wave{wave} ({oracle.arch}): {res['cases_ok']}/{res['cases_total']} ds_permute_b32 cases exact")
184 if args.json_out:
185 with open(args.json_out, "w", encoding="utf-8", newline="\n") as f:
186 json.dump(out, f, indent=2)
187 return 1 if mismatches else 0
188
189
190if __name__ == "__main__":
191 if hasattr(sys.stdout, "reconfigure"):
192 sys.stdout.reconfigure(errors="replace")
193 raise SystemExit(main())
diff --git a/tools/f16_trans_sweep.py b/tools/f16_trans_sweep.py
index 96dd542d4..9c279f1e0 100644
--- a/tools/f16_trans_sweep.py
+++ b/tools/f16_trans_sweep.py
@@ -24,8 +24,8 @@ Usage:
24 python -I tools/f16_trans_sweep.py --self-test 24 python -I tools/f16_trans_sweep.py --self-test
25 25
26Exit 0 when the sweep ran (differences from the rule are findings, not failures), 1 when wave32 and wave64 26Exit 0 when the sweep ran (differences from the rule are findings, not failures), 1 when wave32 and wave64
27disagree, 2 on a harness error (a MODE that did not apply, a kernel without its words), 77 when the hardware 27disagree or --json cannot be written, 2 on a harness error (a MODE that did not apply, a kernel without its
28oracle is unavailable. On Linux the 28words), 77 when the hardware oracle is unavailable. On Linux the
29oracle needs LEONIDA_HW_DRM_NODE (docs/shader_validation.md). Nothing here reads game files. 29oracle needs LEONIDA_HW_DRM_NODE (docs/shader_validation.md). Nothing here reads game files.
30""" 30"""
31import argparse 31import argparse
@@ -385,6 +385,43 @@ def self_test():
385 return 0 385 return 0
386 386
387 387
388def validate_json_path(path):
389 """Return an error string if `path` cannot be used as a --json output file, or None."""
390 if not path or not path.strip():
391 return "--json path must not be empty"
392 if "\x00" in path:
393 return "--json path contains a NUL byte"
394 if path.endswith(os.sep) or (os.altsep and path.endswith(os.altsep)) or os.path.isdir(path):
395 return f"--json path is a directory: {path}"
396 cur = os.path.dirname(os.path.abspath(path))
397 while cur:
398 if os.path.isdir(cur):
399 break
400 if os.path.lexists(cur):
401 return f"--json parent is not a directory: {cur}"
402 nxt = os.path.dirname(cur)
403 if nxt == cur:
404 break
405 cur = nxt
406 return None
407
408
409def write_json_report(path, report):
410 """Create missing parent directories and write `report` as LF-terminated JSON, or return an error string."""
411 parent = os.path.dirname(os.path.abspath(path))
412 if parent:
413 try:
414 os.makedirs(parent, exist_ok=True)
415 except OSError as e:
416 return f"cannot create directory for --json {path}: {e.strerror or e}"
417 try:
418 with open(path, "w", encoding="utf-8", newline="\n") as f:
419 json.dump(report, f, indent=1)
420 except OSError as e:
421 return f"cannot write --json {path}: {e.strerror or e}"
422 return None
423
424
388def main(argv=None): 425def main(argv=None):
389 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) 426 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
390 ap.add_argument("--ops", default=",".join(OPS)) 427 ap.add_argument("--ops", default=",".join(OPS))
@@ -403,6 +440,11 @@ def main(argv=None):
403 if w not in (32, 64)] 440 if w not in (32, 64)]
404 if bad: 441 if bad:
405 ap.error("unknown: " + ", ".join(bad)) 442 ap.error("unknown: " + ", ".join(bad))
443 if a.json is not None:
444 err = validate_json_path(a.json)
445 if err:
446 print(f"error: {err}", file=sys.stderr)
447 return 1
406 from hw_oracle import runner 448 from hw_oracle import runner
407 try: 449 try:
408 oracle = runner.open_oracle(arch=a.hw_arch) 450 oracle = runner.open_oracle(arch=a.hw_arch)
@@ -453,9 +495,11 @@ def main(argv=None):
453 return 2 495 return 2
454 finally: 496 finally:
455 oracle.close() 497 oracle.close()
456 if a.json: 498 if a.json is not None:
457 with open(a.json, "w", encoding="utf-8", newline="\n") as f: 499 err = write_json_report(a.json, report)
458 json.dump(report, f, indent=1) 500 if err:
501 print(f"error: {err}", file=sys.stderr)
502 return 1
459 return rc 503 return rc
460 504
461 505
diff --git a/tools/f32_fuzz.py b/tools/f32_fuzz.py
index 09d464530..2f6e593e7 100644
--- a/tools/f32_fuzz.py
+++ b/tools/f32_fuzz.py
@@ -824,15 +824,15 @@ HW_PRIMARY = "flush"
824 824
825 825
826# Ops whose omod does not depend on the f32 denormal mode: the transcendental unit and the cube ops flush or select 826# Ops whose omod does not depend on the f32 denormal mode: the transcendental unit and the cube ops flush or select
827# whatever MODE says, and gfx1150 applies their omod with denormals kept (measured, 'omod' table). 827# whatever MODE says, and gfx1150 and gfx1031 (RDNA2) apply their omod with denormals kept (measured, 'omod' table).
828OMOD_IGNORES_DENORM_MODE = ("v_rcp_f32", "v_rcp_iflag_f32", "v_rsq_f32", "v_sqrt_f32", "v_exp_f32", "v_log_f32", 828OMOD_IGNORES_DENORM_MODE = ("v_rcp_f32", "v_rcp_iflag_f32", "v_rsq_f32", "v_sqrt_f32", "v_exp_f32", "v_log_f32",
829 "v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32") 829 "v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32", "v_cubema_f32")
830 830
831 831
832def omod_active(mode, op=None): 832def omod_active(mode, op=None):
833 """Whether mul:2 / mul:4 / div:2 act in this mode (measured on gfx1150): never with MODE.IEEE = 1 (LLVM's 833 """Whether mul:2 / mul:4 / div:2 act in this mode (measured on gfx1150 and gfx1031): never with MODE.IEEE = 1
834 SIFoldOperands.cpp: "omod is ignored by hardware if IEEE bit is enabled" and, for f32, if output denormals are 834 (LLVM's SIFoldOperands.cpp: "omod is ignored by hardware if IEEE bit is enabled" and, for f32, if output denormals
835 enabled), and for the ALU ops only with f32 denormals flushed.""" 835 are enabled), and for the ALU ops only with f32 denormals flushed."""
836 m = HW_MODES[mode] 836 m = HW_MODES[mode]
837 return not m["ieee"] and (op in OMOD_IGNORES_DENORM_MODE or not m["denorm32"]) 837 return not m["ieee"] and (op in OMOD_IGNORES_DENORM_MODE or not m["denorm32"])
838 838
@@ -931,9 +931,10 @@ def hw_same(want, got, op=None):
931# that equals the deviation's words is filed under "known deviation", not "match"; anything else stays a mismatch. 931# that equals the deviation's words is filed under "known deviation", not "match"; anything else stays a mismatch.
932 932
933def dev_omod_neg_zero(case, want, mode=None): 933def dev_omod_neg_zero(case, want, mode=None):
934 """On gfx1150 VOP3 omod (mul:2, mul:4, div:2) turns a -0 result into +0 (RDNA2 unmeasured). LLVM notes that omod 934 """VOP3 omod (mul:2, mul:4, div:2) turns a -0 result into +0, on gfx1150 and on RDNA2 (gfx1031, gfx1036). LLVM
935 mishandles signed zeros (SIFoldOperands.cpp) and D30209 describes -0 being forced to +0 before the modifier. Only 935 notes that omod mishandles signed zeros (SIFoldOperands.cpp) and D30209 describes -0 being forced to +0 before the
936 where the omod was active: not with MODE.IEEE = 1, not for ALU ops with f32 denormals kept (omod_active).""" 936 modifier. Only where the omod was active: not with MODE.IEEE = 1, not for ALU ops with f32 denormals kept
937 (omod_active)."""
937 if mode is None: 938 if mode is None:
938 mode = HW_PRIMARY 939 mode = HW_PRIMARY
939 if want[0] == 0x80000000 and any(m in OMOD for m in case.out_mods) and omod_active(mode, case.op): 940 if want[0] == 0x80000000 and any(m in OMOD for m in case.out_mods) and omod_active(mode, case.op):
@@ -1104,6 +1105,8 @@ def omod_label(case, got):
1104 return None 1105 return None
1105 if hw_same(with_, without, case.op) and with_[0] != 0x80000000: 1106 if hw_same(with_, without, case.op) and with_[0] != 0x80000000:
1106 return None 1107 return None
1108 if hw_same(with_, without, case.op) and hw_same(with_, got, case.op):
1109 return "-0 result kept (applied or ignored, same word)" # neither applied nor ignored is shown
1107 if hw_same(with_, got, case.op): 1110 if hw_same(with_, got, case.op):
1108 return "applied" 1111 return "applied"
1109 alt = dev_omod_neg_zero(case, with_) 1112 alt = dev_omod_neg_zero(case, with_)
@@ -1511,7 +1514,7 @@ def info_print(rep):
1511 for (mode, label), n in rep.omod.items(): 1514 for (mode, label), n in rep.omod.items():
1512 tab.setdefault(label, {})[mode] = n 1515 tab.setdefault(label, {})[mode] = n
1513 for label, by in sorted(tab.items()): 1516 for label, by in sorted(tab.items()):
1514 print(f" {label:40s} " + " ".join(f"{m}={by.get(m, 0)}" for m in modes)) 1517 print(f" {label:47s} " + " ".join(f"{m}={by.get(m, 0)}" for m in modes))
1515 if rep.nan: 1518 if rep.nan:
1516 print("\n NaN handling (programs without clamp or omod; same program counts in every mode, so a column that " 1519 print("\n NaN handling (programs without clamp or omod; same program counts in every mode, so a column that "
1517 "differs is a mode effect)") 1520 "differs is a mode effect)")
diff --git a/tools/first_light.py b/tools/first_light.py
index c81c1d6d7..bb720fe20 100644
--- a/tools/first_light.py
+++ b/tools/first_light.py
@@ -460,6 +460,15 @@ def main(argv=None) -> int:
460 os.path.join(work, "first_light", "spirv", f"{stem}.spv"), 460 os.path.join(work, "first_light", "spirv", f"{stem}.spv"),
461 os.path.join(out_dir, f"{stage}.spv"), 461 os.path.join(out_dir, f"{stage}.spv"),
462 ) 462 )
463 # For d3d12_first_light_test: the game's containers (the PSO finds each stage by the FSSM hash inside) and
464 # the translator's index entries, keyed vs/ps so the runtime's shader library reads vs.spv and ps.spv here.
465 for entry in picked:
466 shutil.copy(
467 os.path.join(work, "shaders", "dxbc", entry["file"]),
468 os.path.join(out_dir, f"{entry['stage']}.dxbc"),
469 )
470 with open(os.path.join(out_dir, "index.json"), "w", encoding="utf-8", newline="\n") as f:
471 json.dump({"vs": meta["vs"], "ps": meta["ps"]}, f, indent=1)
463 vertices, indices = read_obj(a.obj) if a.obj else ([], []) 472 vertices, indices = read_obj(a.obj) if a.obj else ([], [])
464 obj_sha256 = None 473 obj_sha256 = None
465 if a.obj: 474 if a.obj:
@@ -501,7 +510,14 @@ def main(argv=None) -> int:
501 "clear_pixel": clear, 510 "clear_pixel": clear,
502 "uv_probes": probes, 511 "uv_probes": probes,
503 "clear": -1.0, 512 "clear": -1.0,
504 "files": {"vs": "vs.spv", "ps": "ps.spv", "mesh": "mesh.bin"}, 513 "files": {
514 "vs": "vs.spv",
515 "ps": "ps.spv",
516 "mesh": "mesh.bin",
517 "vs_dxbc": "vs.dxbc",
518 "ps_dxbc": "ps.dxbc",
519 "index": "index.json",
520 },
505 } 521 }
506 with open(os.path.join(out_dir, "manifest.json"), "w", encoding="utf-8", newline="\n") as f: 522 with open(os.path.join(out_dir, "manifest.json"), "w", encoding="utf-8", newline="\n") as f:
507 json.dump(manifest, f, indent=1) 523 json.dump(manifest, f, indent=1)
diff --git a/tools/fssm_unpack.py b/tools/fssm_unpack.py
index 1a462144c..acaa8705a 100644
--- a/tools/fssm_unpack.py
+++ b/tools/fssm_unpack.py
@@ -21,7 +21,7 @@ The FSSM blob is the precompiled RDNA2 program plus its metadata. It contains th
21the code. 21the code.
22 22
23Usage: 23Usage:
24 python -I fssm_unpack.py <carved_shader_dir> [--payload first|last] 24 python -I fssm_unpack.py <carved_shader_dir> [--carve-index FILE] [--payload first|last]
25 (writes <dir>/fssm/<name>.fssm and fssm_index.json) 25 (writes <dir>/fssm/<name>.fssm and fssm_index.json)
26""" 26"""
27import argparse 27import argparse
@@ -32,6 +32,9 @@ import sys
32import zlib 32import zlib
33from collections import Counter 33from collections import Counter
34 34
35sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
36from shader_stage_manifest import shader_stems # noqa: E402
37
35# Defensive per-blob ceiling, not a maximum defined by the XBCH format. 38# Defensive per-blob ceiling, not a maximum defined by the XBCH format.
36# 64 MiB matches the repository's existing per-resource cap in tools/world_index.py. 39# 64 MiB matches the repository's existing per-resource cap in tools/world_index.py.
37MAX_FSSM_BYTES = 64 << 20 40MAX_FSSM_BYTES = 64 << 20
@@ -107,6 +110,7 @@ def unpack(dxbc: bytes, payload: str = "last"):
107def main(argv=None) -> int: 110def main(argv=None) -> int:
108 ap = argparse.ArgumentParser(description="Unpack the FSSM program from each carved shader container.") 111 ap = argparse.ArgumentParser(description="Unpack the FSSM program from each carved shader container.")
109 ap.add_argument("src", help="carved shader directory") 112 ap.add_argument("src", help="carved shader directory")
113 ap.add_argument("--carve-index", help="unpack only the DXBC files listed in this carve index")
110 ap.add_argument("--payload", choices=("first", "last"), default="last", 114 ap.add_argument("--payload", choices=("first", "last"), default="last",
111 help="tag-0x0D payload when a container has more than one (default: last)") 115 help="tag-0x0D payload when a container has more than one (default: last)")
112 a = ap.parse_args(argv) 116 a = ap.parse_args(argv)
@@ -117,18 +121,24 @@ def main(argv=None) -> int:
117 print(f"ERROR: {src} {what}. Give the folder with the carved .dxbc files.", file=sys.stderr) 121 print(f"ERROR: {src} {what}. Give the folder with the carved .dxbc files.", file=sys.stderr)
118 return 2 122 return 2
119 try: 123 try:
120 with os.scandir(src) as entries: 124 if a.carve_index:
121 shaders = sorted((entry for entry in entries 125 names = shader_stems(a.carve_index, "file", ".dxbc")
122 if entry.name.endswith(".dxbc") and entry.is_file()), 126 shaders = sorted(os.path.join(src, name + ".dxbc") for name in names)
123 key=lambda entry: entry.name) 127 for path in shaders:
124 except OSError as e: 128 if not os.path.isfile(path):
125 print(f"ERROR: cannot list {src}: {e.strerror or e}", file=sys.stderr) 129 raise ValueError(f"{a.carve_index}: declared shader file is missing: {path}")
130 else:
131 with os.scandir(src) as entries:
132 shaders = sorted(entry.path for entry in entries
133 if entry.name.endswith(".dxbc") and entry.is_file())
134 except (OSError, ValueError) as e:
135 print(f"ERROR: cannot list shaders in {src}: {e}", file=sys.stderr)
126 return 2 136 return 2
127 out = os.path.join(src, "fssm") 137 out = os.path.join(src, "fssm")
128 os.makedirs(out, exist_ok=True) 138 os.makedirs(out, exist_ok=True)
129 rows, problems = [], Counter() 139 rows, problems = [], Counter()
130 for shader in shaders: 140 for shader in shaders:
131 with open(shader.path, "rb") as f: 141 with open(shader, "rb") as f:
132 d = f.read() 142 d = f.read()
133 try: 143 try:
134 fssm, ents = unpack(d, payload=a.payload) 144 fssm, ents = unpack(d, payload=a.payload)
@@ -138,7 +148,7 @@ def main(argv=None) -> int:
138 if fssm is None: 148 if fssm is None:
139 problems["no XBCH"] += 1 149 problems["no XBCH"] += 1
140 continue 150 continue
141 stem = shader.name[:-5] 151 stem = os.path.basename(shader)[:-5]
142 with open(os.path.join(out, stem + ".fssm"), "wb") as f: 152 with open(os.path.join(out, stem + ".fssm"), "wb") as f:
143 f.write(fssm) 153 f.write(fssm)
144 ends = [i for i in range(0, len(fssm) - 3, 4) if fssm[i:i + 4] == b"\x00\x00\x81\xbf"] 154 ends = [i for i in range(0, len(fssm) - 3, 4) if fssm[i:i + 4] == b"\x00\x00\x81\xbf"]
diff --git a/tools/gamedata_index.py b/tools/gamedata_index.py
index 12105bd13..a8a7a502b 100644
--- a/tools/gamedata_index.py
+++ b/tools/gamedata_index.py
@@ -28,10 +28,13 @@ import re
28import subprocess 28import subprocess
29import sys 29import sys
30import tempfile 30import tempfile
31import unicodedata
32import zlib 31import zlib
33from collections import defaultdict 32from collections import defaultdict
34 33
34# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module.
35sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
36from report_paths import same_report_path # noqa: E402
37
35ROOT = os.path.dirname(os.path.abspath(__file__)) 38ROOT = os.path.dirname(os.path.abspath(__file__))
36CARVER = os.path.join(ROOT, "rpf9_carve.py") 39CARVER = os.path.join(ROOT, "rpf9_carve.py")
37BOM = b"\xef\xbb\xbf" 40BOM = b"\xef\xbb\xbf"
@@ -237,7 +240,10 @@ def build_rows(rows: list, source) -> list:
237 group = [i] 240 group = [i]
238 detail = magic_name(data) 241 detail = magic_name(data)
239 j = i + 1 242 j = i + 1
240 while j < n and rows[j - 1]["size"] == 65536: 243 # A resource's first stream may be any whole number of 64 KiB blocks (docs/page_directory.md: 128 and
244 # 192 KiB first streams continue in the next one). Only these headed kinds take that rule: a binary,
245 # text or XML run has no header proving a continuation, so it keeps the exact 64 KiB rule below.
246 while j < n and rows[j - 1]["size"] and rows[j - 1]["size"] % 65536 == 0:
241 nxt = source.read(rows[j]) 247 nxt = source.read(rows[j])
242 nk = stream_kind(nxt, rows[j]) 248 nk = stream_kind(nxt, rows[j])
243 if nk in ("decl", "bink2", "rbf0", "psin", "other"): 249 if nk in ("decl", "bink2", "rbf0", "psin", "other"):
@@ -357,42 +363,6 @@ def write_csv(path: str, rows: list) -> None:
357 w.writerows(rows) 363 w.writerows(rows)
358 364
359 365
360_PC_CASE_SENSITIVE = 11 # <sys/unistd.h> on macOS; os.pathconf_names doesn't list it
361
362
363def _case_insensitive_volume(path):
364 """True when the volume that will hold `path` ignores letter case, as macOS's default APFS volume does.
365 os.path.normcase folds case only on Windows, so on macOS `R.json` and `r.json` would pass as two reports."""
366 if sys.platform != "darwin":
367 return False
368 while not os.path.exists(path):
369 parent = os.path.dirname(path)
370 if parent == path:
371 break
372 path = parent
373 try:
374 return os.pathconf(path, _PC_CASE_SENSITIVE) == 0
375 except (OSError, ValueError):
376 return True # the macOS default; folding can only refuse a pair, never overwrite one
377
378
379def _path_key(path):
380 path = os.path.normcase(os.path.realpath(path))
381 if _case_insensitive_volume(path):
382 # APFS and HFS+ also treat composed and decomposed accents as one name.
383 path = unicodedata.normalize("NFD", path.casefold())
384 return path
385
386
387def same_report_path(first: str, second: str) -> bool:
388 if _path_key(first) == _path_key(second):
389 return True
390 try:
391 return os.path.samefile(first, second)
392 except OSError:
393 return False
394
395
396def main() -> int: 366def main() -> int:
397 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) 367 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
398 ap.add_argument("target", help="carve directory or .rpf archive") 368 ap.add_argument("target", help="carve directory or .rpf archive")
diff --git a/tools/gamedata_maps.py b/tools/gamedata_maps.py
index 56fa68ca0..b8f80ebe9 100644
--- a/tools/gamedata_maps.py
+++ b/tools/gamedata_maps.py
@@ -56,12 +56,19 @@ Both formats scale a u8 value into the header's Z box:
56files). Only header fields, dimensions, row counts and value ranges are 56files). Only header fields, dimensions, row counts and value ranges are
57printed or written; the height bytes are not. Standard library only. 57printed or written; the height bytes are not. Standard library only.
58""" 58"""
59from __future__ import annotations
60
59import argparse 61import argparse
60import json 62import json
61import math 63import math
62import os 64import os
63import struct 65import struct
64import sys 66import sys
67import unicodedata
68
69# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module.
70sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
71from report_paths import same_report_path # noqa: E402
65 72
66MAGIC = (b"MHIU", b"PAMH", b"SPS1Z") 73MAGIC = (b"MHIU", b"PAMH", b"SPS1Z")
67HEADER = 44 74HEADER = 44
@@ -314,10 +321,15 @@ def _join(row: dict, data: bytes) -> dict:
314 return out 321 return out
315 322
316 323
317def read_payloads(directory: str) -> list[dict]: 324def _read_index_rows(directory: str) -> list[dict]:
318 with open(os.path.join(directory, "index.json"), encoding="utf-8") as f: 325 with open(os.path.join(directory, "index.json"), encoding="utf-8") as f:
319 index = json.load(f) 326 index = json.load(f)
320 rows = sorted(index["files"], key=lambda r: r["off"]) 327 return sorted(index["files"], key=lambda r: r["off"])
328
329
330def read_payloads(directory: str, rows: list[dict] | None = None) -> list[dict]:
331 if rows is None:
332 rows = _read_index_rows(directory)
321 out = [] 333 out = []
322 i = 0 334 i = 0
323 while i < len(rows): 335 while i < len(rows):
@@ -331,7 +343,8 @@ def read_payloads(directory: str) -> list[dict]:
331 size = len(data) 343 size = len(data)
332 parts = [data] 344 parts = [data]
333 j = i 345 j = i
334 while size < target_size and rows[j].get("size") == 65536 and j + 1 < len(rows): 346 # The header's size bounds the join, so any whole number of 64 KiB blocks may continue (as in gamedata_index).
347 while size < target_size and rows[j].get("size", 0) and rows[j]["size"] % 65536 == 0 and j + 1 < len(rows):
335 nxt = _read_row(directory, rows[j + 1]) 348 nxt = _read_row(directory, rows[j + 1])
336 if nxt[:4] in MAGIC or nxt.startswith((b"<?xml", b"\xef\xbb\xbf<")): 349 if nxt[:4] in MAGIC or nxt.startswith((b"<?xml", b"\xef\xbb\xbf<")):
337 break 350 break
@@ -350,6 +363,137 @@ def _public(payload: dict) -> dict:
350 return {k: v for k, v in payload.items() if not k.startswith("_")} 363 return {k: v for k, v in payload.items() if not k.startswith("_")}
351 364
352 365
366_PC_CASE_SENSITIVE = 11 # <sys/unistd.h> on macOS; os.pathconf_names doesn't list it
367
368
369def _resolve_report_path(path: str) -> str:
370 if os.name != "nt":
371 return os.path.realpath(path)
372 if not path.startswith("\\\\?\\"):
373 # GetFullPathName normalizes ordinary Windows paths the same way opening them does.
374 return os.path.realpath(os.path.abspath(path))
375 # realpath can trim literal trailing dots and spaces from missing verbatim components.
376 # Resolve the existing ancestor and append the missing components as written.
377 missing = []
378 while not os.path.lexists(path):
379 parent, name = os.path.split(path)
380 if not name:
381 break
382 missing.append(name)
383 path = parent
384 return os.path.join(os.path.realpath(path), *reversed(missing))
385
386
387def _case_insensitive_volume(path: str) -> bool:
388 """True when the volume that will hold `path` ignores letter case, as macOS's default APFS volume does.
389 os.path.normcase folds case only on Windows, so on macOS `INDEX.JSON` and `index.json` would otherwise
390 look like two different paths."""
391 if sys.platform != "darwin":
392 return False
393 while not os.path.exists(path):
394 parent = os.path.dirname(path)
395 if parent == path:
396 break
397 path = parent
398 try:
399 return os.pathconf(path, _PC_CASE_SENSITIVE) == 0
400 except (OSError, ValueError):
401 return True # the macOS default; folding can only refuse a collision, never overwrite an input
402
403
404def _path_key(path: str) -> str:
405 path = os.path.normcase(_resolve_report_path(path))
406 if os.name != "nt":
407 if _case_insensitive_volume(path):
408 # APFS and HFS+ also treat composed and decomposed accents as one name.
409 path = unicodedata.normalize("NFD", path.casefold())
410 return path
411 # Drive and UNC paths can also be spelled using the extended-length prefix.
412 extended_prefix = "\\\\?\\"
413 unc_prefix = extended_prefix + "unc\\"
414 if path.startswith(unc_prefix):
415 return "\\\\" + path[len(unc_prefix):]
416 drive, _ = os.path.splitdrive(path)
417 if drive.startswith(extended_prefix) and len(drive) == len(extended_prefix) + 2 and drive.endswith(":"):
418 return path[len(extended_prefix):]
419 return path
420
421
422def _file_identity(path: str):
423 try:
424 st = os.stat(path)
425 except OSError:
426 return None
427 return st.st_dev, st.st_ino
428
429
430def _matches_candidate(out_key: str, out_id, out_in_carve: bool, out_name_folded: str,
431 candidate: str, name: str, is_symlink: bool | None = None) -> bool:
432 if out_id is not None:
433 cand_id = _file_identity(candidate)
434 if cand_id is not None and cand_id == out_id:
435 return True
436 if is_symlink is None:
437 is_symlink = os.path.islink(candidate)
438 if is_symlink:
439 return _path_key(candidate) == out_key
440 if out_in_carve and unicodedata.normalize("NFD", name.casefold()) == out_name_folded:
441 return _path_key(candidate) == out_key
442 return False
443
444
445def check_report_path(out_path: str, carve_dir: str, rows: list[dict] | None = None) -> None:
446 """Refuse a --json path that points to an existing directory or collides with any carve input."""
447 if same_report_path(out_path, carve_dir):
448 raise ValueError(f"--json would overwrite the input {carve_dir}")
449 if os.path.isdir(out_path):
450 raise ValueError(f"--json is a directory: {out_path}")
451 index_path = os.path.join(carve_dir, "index.json")
452 if same_report_path(out_path, index_path):
453 raise ValueError(f"--json would overwrite the input {index_path}")
454
455 out_key = _path_key(out_path)
456 out_id = _file_identity(out_path)
457 carve_key = _path_key(carve_dir)
458 out_in_carve = os.path.dirname(out_key) == carve_key
459 out_name_folded = unicodedata.normalize("NFD", os.path.basename(out_key).casefold())
460
461 if rows is None:
462 if not os.path.isdir(carve_dir):
463 return
464 try:
465 entries = os.scandir(carve_dir)
466 except OSError:
467 return
468 with entries:
469 for entry in entries:
470 if not entry.name.lower().endswith(".bin"):
471 continue
472 try:
473 if entry.is_dir():
474 continue
475 is_link = entry.is_symlink()
476 except OSError:
477 continue
478 if _matches_candidate(out_key, out_id, out_in_carve, out_name_folded,
479 entry.path, entry.name, is_link):
480 raise ValueError(f"--json would overwrite the input {entry.path}")
481 else:
482 for row in rows:
483 name = f'{row["off"]:012x}.bin'
484 candidate = os.path.join(carve_dir, name)
485 if _matches_candidate(out_key, out_id, out_in_carve, out_name_folded,
486 candidate, name):
487 raise ValueError(f"--json would overwrite the input {candidate}")
488
489
490def _make_parent(path: str) -> None:
491 """Create the folder an output path lives in so a missing folder does not lose a finished scan."""
492 parent = os.path.dirname(os.path.abspath(path))
493 if parent:
494 os.makedirs(parent, exist_ok=True)
495
496
353def main() -> int: 497def main() -> int:
354 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) 498 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
355 ap.add_argument("carve_dir", help="rpf9_carve.py output directory") 499 ap.add_argument("carve_dir", help="rpf9_carve.py output directory")
@@ -357,7 +501,12 @@ def main() -> int:
357 a = ap.parse_args() 501 a = ap.parse_args()
358 502
359 try: 503 try:
360 payloads = read_payloads(a.carve_dir) 504 if a.json:
505 check_report_path(a.json, a.carve_dir)
506 rows = _read_index_rows(a.carve_dir)
507 if a.json:
508 check_report_path(a.json, a.carve_dir, rows=rows)
509 payloads = read_payloads(a.carve_dir, rows=rows)
361 except (OSError, ValueError, KeyError, TypeError, struct.error) as e: 510 except (OSError, ValueError, KeyError, TypeError, struct.error) as e:
362 print("error:", e, file=sys.stderr) 511 print("error:", e, file=sys.stderr)
363 return 1 512 return 1
@@ -385,6 +534,7 @@ def main() -> int:
385 if census: 534 if census:
386 out["pamh_census"] = census 535 out["pamh_census"] = census
387 try: 536 try:
537 _make_parent(a.json)
388 with open(a.json, "w", encoding="utf-8", newline="\n") as f: 538 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
389 json.dump(out, f, indent=1) 539 json.dump(out, f, indent=1)
390 except OSError as e: 540 except OSError as e:
diff --git a/tools/gamedata_reader.py b/tools/gamedata_reader.py
new file mode 100644
index 000000000..06c3ff972
--- /dev/null
+++ b/tools/gamedata_reader.py
@@ -0,0 +1,279 @@
1"""Stream the game-data XML of a carved RPF9 archive into Python values, dispatching on root tag and ``type``.
2
3The XML in ``common.rpf`` is RAGE parser metadata (docs/gamedata.md): 118 root tags and 5,293 element tags, written
4with a handful of conventions. This reader turns any of it into plain values without a schema per tag, and lets a
5caller plug in a schema where one is known:
6
7- ``<x value="1.5"/>``: a scalar (bool for ``true``/``false``, int for decimal or ``0x`` hex, float, else the text);
8- ``<v x=".." y=".." [z=".." [w=".."]]/>``: a vector, as a tuple of floats;
9- ``<a content="short_array|float_array|float16_array|vector2_array|vec3v_array|matrix33|matrix34">..</a>``: the
10 whitespace-separated numbers of the body (pairs, triples or matrix rows where the content says so);
11- ``<Item type="CSomeClass">..</Item>``: a polymorphic object, ``{"$type": "CSomeClass", ...}``; ``type="NULL"`` is
12 ``None``;
13- ``<x ref="name"/>``: ``{"$ref": "name"}``;
14- children that are all ``<Item>``: a list; children that all carry ``key``: a dict by key; repeated tags: a list;
15- an element with only text: the text.
16
17Dispatch: ``register_root(tag)`` registers a handler for a whole document's root element, ``register_type(name)``
18one for every element with ``type="name"`` (both called as ``handler(element, reader)``; ``reader.convert`` gives the
19generic value of a sub-element). Everything else takes the generic conversion. The documents are read with
20``iterparse`` and each top-level field is converted and dropped as soon as it ends, so memory is bounded by the largest
21field, not the document.
22
23 python -I tools/gamedata_reader.py <carve_dir or .xml> [...] [--root TAG] [--out DIR]
24
25prints counts only: documents read, roots, the elements each convention covered, ``type`` classes seen, and
26documents that are not well-formed XML (tail-only or truncated carves), with the reason. ``--out DIR`` writes one JSON
27file per document: those files hold the game's data and stay on the local machine (CONTRIBUTING.md). Standard
28library only.
29"""
30import argparse
31import io
32import json
33import os
34import re
35import sys
36import xml.etree.ElementTree as ET
37from collections import Counter
38
39HERE = os.path.dirname(os.path.abspath(__file__))
40if HERE not in sys.path:
41 sys.path.insert(0, HERE)
42
43BOM = b"\xef\xbb\xbf"
44VECTOR_KEYS = ("x", "y", "z", "w")
45CONVENTION_KEYS = frozenset(("type", "content", "value", "ref", "key") + VECTOR_KEYS)
46GROUPS = {"vector2_array": 2, "vec3v_array": 3, "matrix33": 3, "matrix34": 3}
47INT = re.compile(r"[-+]?\d+")
48HEX = re.compile(r"0x[0-9A-Fa-f]+")
49FLOAT = re.compile(r"[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?f?|[-+]?(inf|nan)", re.I)
50
51ROOT_HANDLERS = {}
52TYPE_HANDLERS = {}
53
54
55def register_root(tag):
56 """Decorator: ``handler(element, reader)`` for every document whose root element is ``tag``."""
57 def wrap(fn):
58 ROOT_HANDLERS[tag] = fn
59 return fn
60 return wrap
61
62
63def register_type(name):
64 """Decorator: ``handler(element, reader)`` for every element with ``type="name"``."""
65 def wrap(fn):
66 TYPE_HANDLERS[name] = fn
67 return fn
68 return wrap
69
70
71def parse_scalar(text):
72 """A ``value`` attribute or array token: bool, int (decimal or 0x hex), float, else the text unchanged."""
73 if text in ("true", "false"):
74 return text == "true"
75 if HEX.fullmatch(text):
76 return int(text, 16)
77 if INT.fullmatch(text):
78 return int(text)
79 if FLOAT.fullmatch(text):
80 return _float(text)
81 return text
82
83
84def _float(text):
85 """A float with an optional C-style ``f`` suffix ("1.5f"); "inf" keeps its f."""
86 try:
87 return float(text)
88 except ValueError:
89 return float(text[:-1])
90
91
92def parse_content(kind, text):
93 """The numbers of a ``content=`` body, grouped into tuples for vector arrays and matrices."""
94 nums = [parse_scalar(t) for t in (text or "").split()]
95 width = GROUPS.get(kind)
96 if not width:
97 return nums
98 if len(nums) % width:
99 raise ValueError(f"{kind}: {len(nums)} numbers is not a multiple of {width}")
100 return [tuple(nums[i:i + width]) for i in range(0, len(nums), width)]
101
102
103class Reader:
104 """Converts elements, counting which convention each one took (``stats``) and the ``type`` classes seen."""
105
106 def __init__(self, root_handlers=None, type_handlers=None):
107 self.root_handlers = ROOT_HANDLERS if root_handlers is None else root_handlers
108 self.type_handlers = TYPE_HANDLERS if type_handlers is None else type_handlers
109 self.stats = Counter()
110 self.types = Counter()
111
112 def convert(self, el, use_type_handler=True):
113 """The generic value of element ``el`` (a registered ``type`` handler first, unless told not to). Attributes
114 no convention uses (``name``, ``userFlags``, ...) are kept as ``"@name"`` entries."""
115 value = self._convert(el, use_type_handler)
116 return self.with_attributes(el.attrib, value)
117
118 def with_attributes(self, attrib, value):
119 extra = {f"@{k}": parse_scalar(v) for k, v in attrib.items() if k not in CONVENTION_KEYS}
120 if not extra:
121 return value
122 self.stats["extra attributes"] += 1
123 if isinstance(value, dict):
124 return {**value, **extra}
125 return {"$value": value, **extra} if value not in ("", None) else extra
126
127 def _convert(self, el, use_type_handler=True):
128 a = el.attrib
129 t = a.get("type")
130 if t == "NULL":
131 self.stats["null"] += 1
132 return None
133 if t is not None:
134 self.types[t] += 1
135 handler = self.type_handlers.get(t) if use_type_handler else None
136 if handler:
137 self.stats["type handler"] += 1
138 return handler(el, self)
139 if "content" in a:
140 self.stats["array"] += 1
141 return parse_content(a["content"], el.text)
142 if "value" in a:
143 self.stats["scalar"] += 1
144 return parse_scalar(a["value"])
145 if "x" in a and all(k in VECTOR_KEYS or k in ("type", "key") for k in a):
146 self.stats["vector"] += 1
147 return tuple(_float(a[k]) for k in VECTOR_KEYS if k in a)
148 if "ref" in a:
149 self.stats["reference"] += 1
150 return {"$ref": a["ref"]}
151 kids = list(el)
152 if not kids:
153 self.stats["text"] += 1
154 return (el.text or "").strip()
155 out = self.children(kids)
156 if t is not None:
157 self.stats["object"] += 1
158 if not isinstance(out, dict):
159 out = {"$items": out}
160 out = {"$type": t, **out}
161 return out
162
163 def children(self, kids):
164 """Child elements as a list (all ``Item``), a dict by ``key`` (all keyed) or a dict by tag."""
165 return self.assemble([(k.tag, k.attrib.get("key"), self.convert(k)) for k in kids])
166
167 def assemble(self, parts):
168 """``(tag, key or None, value)`` of each child, in order -> list, dict by key or dict by tag (a tag that occurs
169 more than once becomes the list of its values)."""
170 if all(tag == "Item" for tag, _, _ in parts):
171 if all(key is not None for _, key, _ in parts):
172 self.stats["map"] += 1
173 return {key: value for _, key, value in parts}
174 self.stats["list"] += 1
175 return [value for _, _, value in parts]
176 self.stats["struct"] += 1
177 out, repeated = {}, set()
178 for tag, _, value in parts:
179 if tag in out:
180 if tag not in repeated:
181 out[tag], repeated = [out[tag]], repeated | {tag}
182 out[tag].append(value)
183 else:
184 out[tag] = value
185 return out
186
187 def read(self, data):
188 """One document (bytes) -> ``(root tag, root type, value)``. Fields are converted as their end tag arrives
189 and then dropped from the tree. Raises ``ET.ParseError`` for a document that is not well-formed."""
190 stream = io.BytesIO(data[len(BOM):] if data.startswith(BOM) else data)
191 depth, root, parts = 0, None, []
192 for event, el in ET.iterparse(stream, events=("start", "end")):
193 if event == "start":
194 depth += 1
195 if root is None:
196 root = el
197 continue
198 depth -= 1
199 if depth == 1 and root.tag not in self.root_handlers:
200 # a top-level field is complete: convert it now and drop its sub-tree
201 parts.append((el.tag, el.attrib.get("key"), self.convert(el)))
202 el.clear()
203 handler = self.root_handlers.get(root.tag)
204 if handler:
205 self.stats["root handler"] += 1
206 return root.tag, root.attrib.get("type"), handler(root, self)
207 if not parts:
208 return root.tag, root.attrib.get("type"), self.convert(root)
209 attrib = dict(root.attrib)
210 value = self.assemble(parts)
211 t = root.attrib.get("type")
212 if t is not None and t != "NULL":
213 self.types[t] += 1
214 if not isinstance(value, dict):
215 value = {"$items": value}
216 value = {"$type": t, **value}
217 return root.tag, t, self.with_attributes(attrib, value)
218
219
220def documents(targets):
221 """XML payloads of carve directories (index.json) or .xml files, as gamedata_xml.load_documents yields them."""
222 import gamedata_xml as gx
223 return gx.load_documents(targets)
224
225
226def run(targets, root_filter=None, out_dir=None, reader=None):
227 """Read every document; returns a summary of counts (no names of entries, no values)."""
228 reader = reader or Reader()
229 roots, failed, read = Counter(), Counter(), 0
230 for n, doc in enumerate(documents(targets)):
231 hint = doc.get("root_hint")
232 if root_filter and hint != root_filter:
233 continue
234 try:
235 tag, _, value = reader.read(doc["data"])
236 except ET.ParseError as e:
237 failed[str(e).split(":")[0]] += 1
238 continue
239 read += 1
240 roots[tag] += 1
241 if out_dir:
242 os.makedirs(out_dir, exist_ok=True)
243 name = doc.get("offset_hex") or doc.get("name") or str(n)
244 with open(os.path.join(out_dir, f"{tag}_{name}.json"), "w", encoding="utf-8", newline="\n") as f:
245 json.dump(value, f, indent=1, default=str)
246 return {"documents": read, "roots": len(roots), "per_root_documents": dict(roots),
247 "not_well_formed": sum(failed.values()), "parse_errors": dict(failed),
248 "elements_by_convention": dict(reader.stats), "type_classes": len(reader.types),
249 "typed_elements": sum(reader.types.values()),
250 "registered": {"roots": len(reader.root_handlers), "types": len(reader.type_handlers)}}
251
252
253def main(argv=None):
254 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
255 ap.add_argument("targets", nargs="+", help="rpf9_carve.py directories (with index.json) or .xml files")
256 ap.add_argument("--root", help="only documents with this root tag")
257 ap.add_argument("--out", help="write one JSON file per document here (game data: keep it local)")
258 a = ap.parse_args(argv)
259 try:
260 s = run(a.targets, a.root, a.out)
261 except FileNotFoundError as e:
262 print(f"ERROR: {e} does not exist", file=sys.stderr)
263 return 2
264 print(f"{s['documents']} documents read, {s['roots']} roots, {s['not_well_formed']} not well-formed "
265 f"{s['parse_errors'] or ''}".rstrip())
266 print("elements by convention:", ", ".join(f"{k} {v}" for k, v in sorted(s["elements_by_convention"].items())))
267 print(f"type classes: {s['type_classes']} ({s['typed_elements']} typed elements); registered handlers: "
268 f"{s['registered']['roots']} roots, {s['registered']['types']} types")
269 if a.out:
270 print(f"wrote {s['documents']} JSON files to {a.out} (game data: keep them local)")
271 return 0
272
273
274if __name__ == "__main__":
275 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
276 sys.stdout.reconfigure(errors="replace")
277 except (AttributeError, ValueError, OSError):
278 pass
279 sys.exit(main())
diff --git a/tools/gamedata_xml.py b/tools/gamedata_xml.py
index f9b73b099..e0b804b4e 100644
--- a/tools/gamedata_xml.py
+++ b/tools/gamedata_xml.py
@@ -25,7 +25,6 @@ import os
25import re 25import re
26import statistics 26import statistics
27import sys 27import sys
28import unicodedata
29import xml.etree.ElementTree as ET 28import xml.etree.ElementTree as ET
30from collections import Counter, defaultdict 29from collections import Counter, defaultdict
31 30
@@ -33,6 +32,7 @@ ROOT = os.path.dirname(os.path.abspath(__file__))
33if ROOT not in sys.path: 32if ROOT not in sys.path:
34 sys.path.insert(0, ROOT) 33 sys.path.insert(0, ROOT)
35import gamedata_index as gi # noqa: E402 34import gamedata_index as gi # noqa: E402
35from report_paths import same_report_path # noqa: E402
36 36
37BOM = b"\xef\xbb\xbf" 37BOM = b"\xef\xbb\xbf"
38MACRO_REF = re.compile(r"\$\(([A-Za-z_][\w.-]*)\)") 38MACRO_REF = re.compile(r"\$\(([A-Za-z_][\w.-]*)\)")
@@ -191,12 +191,24 @@ def scan_xml(data: bytes) -> dict:
191 except (ET.ParseError, LookupError, ValueError) as exc: 191 except (ET.ParseError, LookupError, ValueError) as exc:
192 # The parser also raises LookupError or ValueError for unsupported encoding declarations. 192 # The parser also raises LookupError or ValueError for unsupported encoding declarations.
193 report["error"] = str(exc) 193 report["error"] = str(exc)
194 # The parser stops at the error, so the comments after it would go uncounted (a truncated or tail-only
195 # document): count them in the bytes instead, still skipping comment-like text inside CDATA.
196 report["comments"] = raw_comment_count(data)
194 if ended is not None: 197 if ended is not None:
195 scan_refs(ended.tail, report) 198 scan_refs(ended.tail, report)
196 report["attributes"] = sorted(report["attrs"]) 199 report["attributes"] = sorted(report["attrs"])
197 return report 200 return report
198 201
199 202
203CDATA = re.compile(rb"<!\[CDATA\[.*?(?:\]\]>|\Z)", re.S)
204
205
206def raw_comment_count(data: bytes) -> int:
207 """Comment starts in a document the parser could not finish, outside CDATA sections (an unclosed one runs to
208 the end of the data)."""
209 return CDATA.sub(b"", data).count(b"<!--")
210
211
200def looks_truncated(data: bytes, root: str) -> bool: 212def looks_truncated(data: bytes, root: str) -> bool:
201 """True when the bytes start inside a document instead of at its root element.""" 213 """True when the bytes start inside a document instead of at its root element."""
202 if not root: 214 if not root:
@@ -474,42 +486,6 @@ def _make_parent(path: str) -> None:
474 os.makedirs(parent, exist_ok=True) 486 os.makedirs(parent, exist_ok=True)
475 487
476 488
477_PC_CASE_SENSITIVE = 11 # <sys/unistd.h> on macOS; os.pathconf_names doesn't list it
478
479
480def _case_insensitive_volume(path):
481 """True when the volume that will hold `path` ignores letter case, as macOS's default APFS volume does.
482 os.path.normcase folds case only on Windows, so on macOS `R.json` and `r.json` would pass as two reports."""
483 if sys.platform != "darwin":
484 return False
485 while not os.path.exists(path):
486 parent = os.path.dirname(path)
487 if parent == path:
488 break
489 path = parent
490 try:
491 return os.pathconf(path, _PC_CASE_SENSITIVE) == 0
492 except (OSError, ValueError):
493 return True # the macOS default; folding can only refuse a pair, never overwrite one
494
495
496def _path_key(path):
497 path = os.path.normcase(os.path.realpath(path))
498 if _case_insensitive_volume(path):
499 # APFS and HFS+ also treat composed and decomposed accents as one name.
500 path = unicodedata.normalize("NFD", path.casefold())
501 return path
502
503
504def same_report_path(first: str, second: str) -> bool:
505 if _path_key(first) == _path_key(second):
506 return True
507 try:
508 return os.path.samefile(first, second)
509 except OSError:
510 return False
511
512
513def write_csv(path: str, rows: list) -> None: 489def write_csv(path: str, rows: list) -> None:
514 _make_parent(path) 490 _make_parent(path)
515 fields = ["source", "offset_hex", "bytes", "chunks", "root", "category", "header", "complete", 491 fields = ["source", "offset_hex", "bytes", "chunks", "root", "category", "header", "complete",
diff --git a/tools/gen_d3d12_stubs.py b/tools/gen_d3d12_stubs.py
index 184640d8d..1acd70b8e 100644
--- a/tools/gen_d3d12_stubs.py
+++ b/tools/gen_d3d12_stubs.py
@@ -106,7 +106,8 @@ def implemented_names(paths):
106 names = set() 106 names = set()
107 for path in paths: 107 for path in paths:
108 with open(path, encoding="utf-8", errors="replace") as f: 108 with open(path, encoding="utf-8", errors="replace") as f:
109 names.update(OVERRIDE.findall(f.read())) 109 source = COMMENTS_OR_LITERALS.sub(" ", f.read())
110 names.update(OVERRIDE.findall(source))
110 return names 111 return names
111 112
112 113
@@ -140,6 +141,26 @@ def write_if_changed(path, text):
140 f.write(text) 141 f.write(text)
141 142
142 143
144def same_path(first, second):
145 """True when writing first would replace second (same file, or a case/symlink alias of it)."""
146 if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)):
147 return True
148 try:
149 return os.path.samefile(first, second)
150 except OSError:
151 return False
152
153
154def write_report(path, text):
155 """write_if_changed with a one-line ERROR instead of a traceback; False when it could not write."""
156 try:
157 write_if_changed(path, text)
158 except OSError as e:
159 print(f"ERROR: cannot write {path}: {e}", file=sys.stderr)
160 return False
161 return True
162
163
143def main(): 164def main():
144 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) 165 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
145 parser.add_argument("--out", help="generated stub header (required unless --report is given)") 166 parser.add_argument("--out", help="generated stub header (required unless --report is given)")
@@ -153,15 +174,30 @@ def main():
153 parser.error("--out is required unless --report is given") 174 parser.error("--out is required unless --report is given")
154 if args.report and not args.source: 175 if args.report and not args.source:
155 parser.error("--report needs at least one --source") 176 parser.error("--report needs at least one --source")
177 for path in args.source:
178 if not os.path.isfile(path):
179 parser.error(f"--source {path}: no such file")
180 for path in (args.out, args.report):
181 if path and os.path.isdir(path):
182 parser.error(f"{path} is a folder, not a file")
183 if args.out and args.report and same_path(args.out, args.report):
184 parser.error("--out and --report must use different paths")
156 header = args.header or find_header() 185 header = args.header or find_header()
157 if not header: 186 if not header:
158 raise SystemExit("d3d12.h not found: pass --header or run from a vcvars environment") 187 raise SystemExit("d3d12.h not found: pass --header or run from a vcvars environment")
188 if not os.path.isfile(header):
189 parser.error(f"--header {header}: no such file")
190 for path in [header] + list(args.source):
191 for flag, target in (("--out", args.out), ("--report", args.report)):
192 if target and same_path(target, path):
193 parser.error(f"{flag} {target} would overwrite the input {path}")
159 with open(header, encoding="utf-8", errors="replace") as f: 194 with open(header, encoding="utf-8", errors="replace") as f:
160 interfaces = parse_interfaces(f.read()) 195 interfaces = parse_interfaces(f.read())
161 196
162 if args.report: 197 if args.report:
163 report = coverage(interfaces, args.interfaces, args.source) 198 report = coverage(interfaces, args.interfaces, args.source)
164 write_if_changed(args.report, json.dumps(report, indent=2) + "\n") 199 if not write_report(args.report, json.dumps(report, indent=2) + "\n"):
200 return 2
165 if not args.out: 201 if not args.out:
166 return 0 202 return 0
167 203
@@ -175,7 +211,8 @@ def main():
175 ] 211 ]
176 parts += [emit_class(interfaces, leaf) for leaf in dict.fromkeys(args.interfaces)] 212 parts += [emit_class(interfaces, leaf) for leaf in dict.fromkeys(args.interfaces)]
177 parts.append("#pragma warning(pop)") 213 parts.append("#pragma warning(pop)")
178 write_if_changed(args.out, "\n".join(parts) + "\n") 214 if not write_report(args.out, "\n".join(parts) + "\n"):
215 return 2
179 return 0 216 return 0
180 217
181 218
diff --git a/tools/glb_writer.py b/tools/glb_writer.py
index 813ca1d4f..9a7ee2fc0 100644
--- a/tools/glb_writer.py
+++ b/tools/glb_writer.py
@@ -72,11 +72,15 @@ def _clean_zero(v: float) -> float:
72def _normalize3(nx: float, ny: float, nz: float) -> tuple[float, float, float]: 72def _normalize3(nx: float, ny: float, nz: float) -> tuple[float, float, float]:
73 if not (math.isfinite(nx) and math.isfinite(ny) and math.isfinite(nz)): 73 if not (math.isfinite(nx) and math.isfinite(ny) and math.isfinite(nz)):
74 return (0.0, 1.0, 0.0) 74 return (0.0, 1.0, 0.0)
75 length = math.sqrt(nx * nx + ny * ny + nz * nz) 75 length = math.hypot(nx, ny, nz)
76 if length <= 0.0 or not math.isfinite(length): 76 if length == 0.0:
77 return (0.0, 1.0, 0.0) 77 return (0.0, 1.0, 0.0)
78 inv = 1.0 / length 78 if length < sys.float_info.min or not math.isfinite(length):
79 return (_clean_zero(nx * inv), _clean_zero(ny * inv), _clean_zero(nz * inv)) 79 # Scaling first keeps an unrepresentable or subnormal length from changing the direction.
80 scale = max(abs(nx), abs(ny), abs(nz))
81 nx, ny, nz = nx / scale, ny / scale, nz / scale
82 length = math.hypot(nx, ny, nz)
83 return (_clean_zero(nx / length), _clean_zero(ny / length), _clean_zero(nz / length))
80 84
81 85
82def _compute_smooth_normals( 86def _compute_smooth_normals(
@@ -242,7 +246,7 @@ def parse_obj(
242 # Preserve order of appearance for (group_index, material_name) primitives. 246 # Preserve order of appearance for (group_index, material_name) primitives.
243 builders: dict[tuple[int, str], dict] = {} 247 builders: dict[tuple[int, str], dict] = {}
244 248
245 for raw_line in text.splitlines(): 249 for raw_line in text.removeprefix("\ufeff").splitlines():
246 line = raw_line.strip() 250 line = raw_line.strip()
247 if not line or line[0] == "#": 251 if not line or line[0] == "#":
248 continue 252 continue
diff --git a/tools/hw_oracle/tsharp.py b/tools/hw_oracle/tsharp.py
index 87254af79..8976c51e7 100644
--- a/tools/hw_oracle/tsharp.py
+++ b/tools/hw_oracle/tsharp.py
@@ -18,7 +18,7 @@ Where the layout comes from (facts only; Mesa is MIT-licensed, the code here is
18 LLVM's AMDGPU::UfmtGFX11::UnifiedFormat (SIDefines.h), which Mesa's GFX11_FORMAT follows. 18 LLVM's AMDGPU::UfmtGFX11::UnifiedFormat (SIDefines.h), which Mesa's GFX11_FORMAT follows.
19GFX11 renumbers the formats (8_8_8_8_UNORM is 56 on GFX10 and 42 on GFX11), narrows FORMAT to [27:20], moves MAX_MIP 19GFX11 renumbers the formats (8_8_8_8_UNORM is 56 on GFX10 and 42 on GFX11), narrows FORMAT to [27:20], moves MAX_MIP
20into WORD1 and drops WORD2's RESOURCE_LEVEL bit (GFX10 needs it set). A GFX11 part (the Radeon 880M is gfx1150, RDNA3.5) 20into WORD1 and drops WORD2's RESOURCE_LEVEL bit (GFX10 needs it set). A GFX11 part (the Radeon 880M is gfx1150, RDNA3.5)
21runs these descriptors; RDNA2 (gfx1030) takes the GFX10 ones, which no GPU in the lab has run yet. 21runs these descriptors; RDNA2 (gfx1030) takes the GFX10 ones; a gfx1036 (RDNA2) ran them for tools/texoff_probe.py (2D and 3D, R32_SFLOAT).
22""" 22"""
23import re 23import re
24 24
diff --git a/tools/image_d16_probe.py b/tools/image_d16_probe.py
new file mode 100644
index 000000000..a6e301431
--- /dev/null
+++ b/tools/image_d16_probe.py
@@ -0,0 +1,315 @@
1r"""How an RDNA2 GPU narrows 32-bit integer texels in d16 image loads, per image dimension (SHADER-387). Standard
2library only.
3
4docs/design.md ("Typed image loads") has native gfx1036 saturating 32-bit UINT/SINT texels to the 16-bit range in
52D d16 loads, and lists 1D, 2D-array and 3D d16 loads as unchecked. Mesa sets `integer_dest_saturates` for AMD,
6the translator saturates (`saturate_int16`). This probe measures it natively (through tools/hw_oracle/) on every
7dimension the translator handles: SQ_RSRC_IMG_1D, 2D, 2D_ARRAY and 3D, for the formats 32_UINT and 32_SINT (dmask
80x1) and 32_32_UINT and 32_32_SINT (dmask 0x3, two results packed into one VGPR), with `image_load` and
9`image_load_mip` (mip 0).
10
11Each lane reads one texel. Per texel the kernel stores four words:
12 0 image_load without d16, x channel the control: must be the staged word, or the texture is laid out wrong
13 1 image_load d16 the destination VGPR seeded with 0x5a5a5a5a first
14 2 image_load_mip d16, mip 0 the same, through the other form
15 3 image_load without d16, y channel (two-channel formats; the control for y, else the seed)
16Every d16 result is compared with three rules for each 32-bit input w:
17 trunc the low 16 bits of w (what the translator did before it saturated)
18 sat_u min(w, 0xffff), w unsigned
19 sat_s w as a signed int clamped to [-32768, 32767], its low 16 bits
20and, for one-channel formats, the high half: kept (0x5a5a, as docs/design.md records for 2D) or something else.
21
22The texture rides in the kernel's code after s_endpgm, as tools/hw_oracle/tsharp.py does for 2D, in a linear
23layout whose rows are 256 bytes (64 R32 texels, 32 R32G32 texels), so the layout does not depend on how the T#
24states the pitch. GFX10 only (RDNA1 and RDNA2: the T# layout); another family
25exits 77.
26
27Usage:
28 python -I tools/image_d16_probe.py [--dims 1d,2d,2d_array,3d] [--formats r32_uint,...] [--json out.json]
29 python -I tools/image_d16_probe.py --self-test # the rules, T# words and kernels, no GPU
30
31Exit 0 when the sweep ran (which rule the hardware follows is a finding, not a failure), 1 when image_load and
32image_load_mip disagree, 2 on a harness error (a control word did not read back), 77 when the hardware oracle is
33unavailable or the GPU is not GFX10. Nothing here reads game files.
34"""
35import argparse
36import json
37import os
38import sys
39
40sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
41
42SEED = 0x5A5A5A5A
43SENTINEL = 0xDEAD0000
44POISON = 0xBAADF00D
45ROW_BYTES = 256
46
47# Dimension -> (T# TYPE, MIMG dim name, coordinate count, texture extent as (height, depth or layers)).
48DIMS = {
49 "1d": (8, "SQ_RSRC_IMG_1D", 1, (1, 1)),
50 "2d": (9, "SQ_RSRC_IMG_2D", 2, (2, 1)),
51 "2d_array": (13, "SQ_RSRC_IMG_2D_ARRAY", 3, (2, 3)),
52 "3d": (10, "SQ_RSRC_IMG_3D", 3, (2, 3)),
53}
54# Format -> (GFX10 FORMAT code, channels, signed). Codes from tools/gfx10_formats.json.
55FORMATS = {
56 "r32_uint": (20, 1, False),
57 "r32_sint": (21, 1, True),
58 "r32g32_uint": (62, 2, False),
59 "r32g32_sint": (63, 2, True),
60}
61# Values that tell the rules apart, then a few that every rule maps alike.
62EDGES = [0x00000000, 0x00000001, 0x00007FFE, 0x00007FFF, 0x00008000, 0x00008001, 0x0000FFFE, 0x0000FFFF,
63 0x00010000, 0x00010001, 0x00012345, 0x0001FFFF, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFF7FFF,
64 0xFFFF8000, 0xFFFF8001, 0xFFFFFFFE, 0xFFFFFFFF, 0x12348765, 0xDEAD5A5A, 0x00004321, 0xFFFFC000]
65
66
67def rules(w):
68 """The 16-bit result of each candidate rule for the 32-bit input w."""
69 s = w - (1 << 32) if w & 0x80000000 else w
70 return {"trunc": w & 0xFFFF, "sat_u": min(w, 0xFFFF), "sat_s": max(-32768, min(32767, s)) & 0xFFFF}
71
72
73def texel_values(fmt, count):
74 """The staged 32-bit words, `channels` per texel: EDGES first, then a fixed mixing sequence."""
75 channels = FORMATS[fmt][1]
76 out, x = [], 0x9E3779B9
77 for i in range(count * channels):
78 if i < len(EDGES):
79 out.append(EDGES[i])
80 else:
81 x = (x * 1103515245 + 12345) & 0xFFFFFFFF
82 out.append(x ^ (x >> 7) if i % 3 else EDGES[i % len(EDGES)])
83 return [tuple(out[t * channels:(t + 1) * channels]) for t in range(count)]
84
85
86def geometry(dim, fmt):
87 """(width, height, depth or layers, texel count) of the probe's texture."""
88 channels = FORMATS[fmt][1]
89 width = ROW_BYTES // (4 * channels)
90 height, depth = DIMS[dim][3]
91 return width, height, depth, width * height * depth
92
93
94def image_words(dim, fmt):
95 """The 8 words of a linear, one-mip GFX10.3 T# with the base address left zero (the kernel adds it).
96 Field positions as runtime/src/gfx10_descriptors.h lists them; a 1D or 2D image carries its pitch - 1 in WORD4
97 DEPTH (GFX10.3 linear), an array its last layer and a 3D image its depth - 1."""
98 kind, _, _, _ = DIMS[dim]
99 code = FORMATS[fmt][0]
100 width, height, depth, _ = geometry(dim, fmt)
101 w, h = width - 1, height - 1
102 word1 = (code << 20) | ((w & 3) << 30)
103 word2 = ((w >> 2) & 0xFFF) | (h << 14) | (1 << 31) # RESOURCE_LEVEL, 1 on GFX10
104 word3 = (4 | 5 << 3 | 6 << 6 | 7 << 9) | (kind << 28) # X Y Z W, levels 0..0, linear
105 word4 = (width - 1) if dim in ("1d", "2d") else (depth - 1) # pitch is width: rows are exactly 256 bytes
106 word5 = 4 << 20 # PERF_MOD, as Mesa writes it
107 return [0, word1, word2, word3, word4, word5, 0, 0]
108
109
110def texture_bytes(dim, fmt):
111 data = bytearray()
112 for texel in texel_values(fmt, geometry(dim, fmt)[3]):
113 for word in texel:
114 data += word.to_bytes(4, "little")
115 return bytes(data)
116
117
118def _longs(data):
119 words = [int.from_bytes(data[i:i + 4], "little") for i in range(0, len(data), 4)]
120 return [f" .long {', '.join(f'0x{w:08x}' for w in words[i:i + 8])}" for i in range(0, len(words), 8)]
121
122
123def kernel_lines(dim, fmt, uid=0):
124 """A raw kernel (asm.Kernel(..., raw=True): s[2:3] the output, v0 the lane), one texel per lane."""
125 _, dim_name, ncoord, _ = DIMS[dim]
126 width, height, _, count = geometry(dim, fmt)
127 channels = FORMATS[fmt][1]
128 t = image_words(dim, fmt)
129 log2w, log2wh = width.bit_length() - 1, (width * height).bit_length() - 1
130 addr = "v2" if ncoord == 1 else f"v[2:{1 + ncoord}]"
131 mip = f"v[2:{2 + ncoord}]"
132 d16_mask = "0x1" if channels == 1 else "0x3"
133 out = ["s_getpc_b64 s[4:5]", f".Lpc{uid}:", f"s_add_u32 s4, s4, .Ltex{uid}-.Lpc{uid}", "s_addc_u32 s5, s5, 0",
134 "s_and_b32 s6, s4, 255", "s_lshr_b64 s[4:5], s[4:5], 8", "s_mov_b32 s8, s4", "s_and_b32 s9, s5, 255",
135 f"s_or_b32 s9, s9, 0x{t[1]:08x}"]
136 out += [f"s_mov_b32 s{8 + i}, 0x{t[i]:08x}" for i in range(2, 8)]
137 out += [f"v_and_b32 v2, {width - 1}, v0",
138 f"v_lshrrev_b32 v3, {log2w}, v0",
139 f"v_and_b32 v3, {height - 1}, v3",
140 f"v_lshrrev_b32 v4, {log2wh}, v0",
141 f"v_mov_b32 v{2 + ncoord}, 0"] # the mip of image_load_mip (or unused)
142 if ncoord == 1:
143 out.append("v_mov_b32 v4, 0")
144 out += [f"v_mov_b32 v8, 0x{SENTINEL:08x}", f"v_mov_b32 v9, 0x{SEED:08x}", f"v_mov_b32 v10, 0x{SEED:08x}",
145 f"v_mov_b32 v11, 0x{SEED:08x}",
146 "s_cmp_lg_u32 s6, 0", f"s_cbranch_scc0 .Lok{uid}"]
147 out += [f"v_mov_b32 v{8 + i}, 0x{POISON:08x}" for i in range(4)]
148 out += [f"s_branch .Lst{uid}", f".Lok{uid}:",
149 f"image_load v8, {addr}, s[8:15] dmask:0x1 dim:{dim_name} unorm",
150 f"image_load v9, {addr}, s[8:15] dmask:{d16_mask} dim:{dim_name} unorm d16",
151 f"image_load_mip v10, {mip}, s[8:15] dmask:{d16_mask} dim:{dim_name} unorm d16"]
152 if channels == 2:
153 out.append(f"image_load v11, {addr}, s[8:15] dmask:0x2 dim:{dim_name} unorm")
154 out += ["s_waitcnt vmcnt(0)", f".Lst{uid}:", "v_lshlrev_b32 v6, 4, v0", "global_store_b128 v6, v[8:11], s[2:3]",
155 "s_endpgm", ".p2align 8", f".Ltex{uid}:"]
156 if count > 1024:
157 raise ValueError("one lane per texel needs at most 1024 texels")
158 return out + _longs(texture_bytes(dim, fmt))
159
160
161def classify(dim, fmt, words):
162 """Compare one kernel's output (4 words per texel) with the rules."""
163 channels = FORMATS[fmt][1]
164 staged = texel_values(fmt, geometry(dim, fmt)[3])
165 entry = {"texels": len(staged), "control": [], "forms": {}}
166 forms = {"image_load": 1, "image_load_mip": 2}
167 agree = {f: {r: 0 for r in ("trunc", "sat_u", "sat_s")} for f in forms}
168 high = {f: {} for f in forms}
169 first_off = {f: [] for f in forms}
170 for i, texel in enumerate(staged):
171 got = words[4 * i:4 * i + 4]
172 if got[0] != texel[0]:
173 entry["control"].append(f"texel {i}: x read back 0x{got[0]:08x}, staged 0x{texel[0]:08x}")
174 if channels == 2 and got[3] != texel[1]:
175 entry["control"].append(f"texel {i}: y read back 0x{got[3]:08x}, staged 0x{texel[1]:08x}")
176 for form, k in forms.items():
177 lo, hi = got[k] & 0xFFFF, got[k] >> 16
178 for r in agree[form]:
179 want = rules(texel[0])[r]
180 ok = lo == want
181 if channels == 2:
182 ok = ok and hi == rules(texel[1])[r]
183 agree[form][r] += ok
184 if channels == 1:
185 key = "kept" if hi == SEED >> 16 else f"0x{hi:04x}"
186 high[form][key] = high[form].get(key, 0) + 1
187 if len(first_off[form]) < 4 and not any(
188 (lo == rules(texel[0])[r]) for r in ("sat_u", "sat_s")):
189 first_off[form].append({"in": [f"0x{v:08x}" for v in texel], "got": f"0x{got[k]:08x}"})
190 for form in forms:
191 entry["forms"][form] = {"match": agree[form], "high_half": high[form] or "n/a (two channels)",
192 "first_off": first_off[form]}
193 entry["forms_differ"] = sum(words[4 * i + 1] != words[4 * i + 2] for i in range(len(staged)))
194 return entry
195
196
197def self_test():
198 """The rules on the edge values, the T# fields and the kernels, without a GPU."""
199 fails = []
200
201 def check(cond, what):
202 if not cond:
203 fails.append(what)
204
205 check(rules(0x00012345) == {"trunc": 0x2345, "sat_u": 0xFFFF, "sat_s": 0x7FFF}, "rules of 0x12345")
206 check(rules(0xFFFF8000) == {"trunc": 0x8000, "sat_u": 0xFFFF, "sat_s": 0x8000}, "rules of -32768")
207 check(rules(0x80000000) == {"trunc": 0x0000, "sat_u": 0xFFFF, "sat_s": 0x8000}, "rules of INT_MIN")
208 check(rules(0x00007FFF) == {"trunc": 0x7FFF, "sat_u": 0x7FFF, "sat_s": 0x7FFF}, "rules of 0x7fff")
209 # the edges tell every pair of rules apart, so a match count says which rule the hardware follows
210 for a in ("trunc", "sat_u", "sat_s"):
211 for b in ("trunc", "sat_u", "sat_s"):
212 if a < b:
213 check(any(rules(w)[a] != rules(w)[b] for w in EDGES), f"no edge separates {a} from {b}")
214 for dim in DIMS:
215 for fmt in FORMATS:
216 width, height, depth, count = geometry(dim, fmt)
217 check(width * 4 * FORMATS[fmt][1] == ROW_BYTES, f"{dim} {fmt}: a row is not 256 bytes")
218 t = image_words(dim, fmt)
219 check(t[3] >> 28 == DIMS[dim][0], f"{dim} {fmt}: TYPE")
220 check((t[1] >> 20) & 0x1FF == FORMATS[fmt][0], f"{dim} {fmt}: FORMAT")
221 check(((t[1] >> 30) | ((t[2] & 0xFFF) << 2)) + 1 == width, f"{dim} {fmt}: WIDTH")
222 check(((t[2] >> 14) & 0x3FFF) + 1 == height, f"{dim} {fmt}: HEIGHT")
223 lines = kernel_lines(dim, fmt)
224 check(sum(ln.startswith("image_load") for ln in lines) == 2 + FORMATS[fmt][1], f"{dim} {fmt}: loads")
225 check(all(DIMS[dim][1] in ln for ln in lines if ln.startswith("image_load")), f"{dim} {fmt}: dim")
226 check(len(texture_bytes(dim, fmt)) == count * 4 * FORMATS[fmt][1], f"{dim} {fmt}: texture size")
227 # a fake GPU that saturates: every texel matches sat_s or sat_u, and the controls hold
228 signed = FORMATS[fmt][2]
229 fake = []
230 for texel in texel_values(fmt, count):
231 r = [rules(v)["sat_s" if signed else "sat_u"] for v in texel]
232 d16 = r[0] | ((r[1] << 16) if len(r) == 2 else SEED & 0xFFFF0000)
233 fake += [texel[0], d16, d16, texel[1] if len(texel) == 2 else SEED]
234 e = classify(dim, fmt, fake)
235 rule = "sat_s" if signed else "sat_u"
236 check(not e["control"] and e["forms"]["image_load"]["match"][rule] == count and e["forms_differ"] == 0,
237 f"{dim} {fmt}: the saturating fake does not match {rule}")
238 check(e["forms"]["image_load"]["match"]["trunc"] < count, f"{dim} {fmt}: trunc not told apart")
239 for f in fails:
240 print("FAIL:", f)
241 print(f"self-test: {'ok' if not fails else f'{len(fails)} failure(s)'}")
242 return 1 if fails else 0
243
244
245def main(argv=None):
246 ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
247 ap.add_argument("--dims", default=",".join(DIMS))
248 ap.add_argument("--formats", default=",".join(FORMATS))
249 ap.add_argument("--json", help="write the per-case counts here")
250 ap.add_argument("--hw-arch")
251 ap.add_argument("--self-test", action="store_true")
252 a = ap.parse_args(argv)
253 if a.self_test:
254 return self_test()
255 dims = [d for d in a.dims.split(",") if d]
256 fmts = [f for f in a.formats.split(",") if f]
257 bad = [d for d in dims if d not in DIMS] + [f for f in fmts if f not in FORMATS]
258 if bad or not dims or not fmts:
259 ap.error("unknown or empty: " + ", ".join(bad or ["--dims/--formats"]))
260 from hw_oracle import asm, runner
261 try:
262 oracle = runner.open_oracle(arch=a.hw_arch)
263 except runner.Unavailable as e:
264 print(f"hardware oracle unavailable: {e}")
265 return 77
266 rc = 0
267 try:
268 if asm.family(oracle.arch) != "gfx10":
269 print(f"hardware oracle unavailable: {oracle.arch} is not GFX10; the T# here is GFX10's (RDNA2)")
270 return 77
271 print(f"hardware oracle: {oracle.device}")
272 report = {"device": str(oracle.device), "arch": oracle.arch, "cases": {}}
273 cases = [(d, f) for d in dims for f in fmts]
274 kernels = []
275 for uid, (d, f) in enumerate(cases):
276 count = geometry(d, f)[3]
277 kernels.append(asm.Kernel(kernel_lines(d, f, uid), 32, count, count * 4, raw=True))
278 for (d, f), got in zip(cases, oracle.run(kernels)):
279 name = f"{d} {f}"
280 if isinstance(got, str):
281 print(f"harness error: {name}: {got}")
282 rc = 2
283 continue
284 e = classify(d, f, got)
285 report["cases"][name] = e
286 if e["control"]:
287 rc = 2
288 for c in e["control"][:4]:
289 print(f"harness error: {name}: {c}")
290 if e["forms_differ"] and rc != 2:
291 rc = 1
292 for form, s in e["forms"].items():
293 m = ", ".join(f"{r} {k}/{e['texels']}" for r, k in s["match"].items())
294 hh = s["high_half"] if isinstance(s["high_half"], str) else \
295 ", ".join(f"{k} {v}" for k, v in s["high_half"].items())
296 print(f"{name:<18} {form:<15} {m}; high half: {hh}")
297 if e["forms_differ"]:
298 print(f"{name}: image_load and image_load_mip differ on {e['forms_differ']} texels")
299 except RuntimeError as e:
300 print(f"harness error: {e}")
301 return 2
302 finally:
303 oracle.close()
304 if a.json:
305 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
306 json.dump(report, f, indent=1)
307 return rc
308
309
310if __name__ == "__main__":
311 try:
312 sys.stdout.reconfigure(errors="replace")
313 except (AttributeError, ValueError, OSError):
314 pass
315 sys.exit(main())
diff --git a/tools/image_query_probe.py b/tools/image_query_probe.py
new file mode 100644
index 000000000..29fabe517
--- /dev/null
+++ b/tools/image_query_probe.py
@@ -0,0 +1,307 @@
1r"""What `image_get_resinfo` and `image_get_lod` return on an RDNA2 GPU (SHADER-388). Standard library only.
2
3docs/design.md ("Image atomics, size and LOD queries") left three answers unverified: resinfo's depth word for a 2D
4image, the clamped LOD `image_get_lod` returns under a linear mip filter, and the order of u and v in the LOD query.
5This probe runs both instructions natively (through tools/hw_oracle/) on hand-built descriptors and compares every
6result word with the rules below. Neither instruction reads memory, so the T# has no texture behind it.
7
8image_get_resinfo, dmask 0xf, address VGPR = mip level (unsigned), T# with BASE_LEVEL b and LAST_LEVEL l:
9 n = l - b + 1 levels; past the last level (level >= n) width, height and depth are 0; otherwise
10 width = max(1, WIDTH >> (b + level)), height likewise, and the depth word is
11 2D: 0, whatever T# WORD4 DEPTH holds (a linear GFX10.3 T# keeps its pitch there)
12 2D array: max(1, (DEPTH + 1) >> (b + level)): the layer count is minified like a 3D depth
13 and the fourth word is n.
14image_get_lod, dmask 0x3, 2D, S# MIN_LOD lo, MAX_LOD hi, LOD_BIAS s, n levels; one 2x2 quad of lanes whose u steps
15by du across x and v by dv across y (so the LOD is log2(max(du * width, dv * height))):
16 VGPR 1 (raw) = that LOD + s
17 VGPR 0 (clamped) = 0 with MIP_FILTER none; else c = min(max(min(raw, hi), lo), n - 1) (lo wins over hi when
18 lo > hi, and the level count caps both), then floor(c + 0.5) with MIP_FILTER point (the level it would read,
19 ties up) and c with MIP_FILTER linear.
20That is the definition of OpImageQueryLod / textureQueryLod (the level read, or a fraction between the two read).
21
22Every case runs in wave32 and wave64; every lane of a quad must agree.
23
24Usage:
25 python -I tools/image_query_probe.py [--waves 32,64] [--json out.json]
26 python -I tools/image_query_probe.py --self-test # the rules against values measured on gfx1036, no GPU
27
28Exit 0 when every word matches the rules, 1 on a mismatch (a finding: the rules above are wrong on this GPU), 2 on a
29harness error, 77 when the hardware oracle is unavailable or the GPU is not GFX10 (the T# layout is GFX10's).
30Nothing here reads game files.
31"""
32import argparse
33import json
34import math
35import os
36import struct
37import sys
38
39HERE = os.path.dirname(os.path.abspath(__file__))
40sys.dont_write_bytecode = True
41if HERE not in sys.path:
42 sys.path.insert(0, HERE)
43
44TYPE_2D, TYPE_2D_ARRAY = 9, 10 # SQ_RSRC_IMG_* in T# WORD3 [31:28]
45DIMS = {TYPE_2D: "SQ_RSRC_IMG_2D", TYPE_2D_ARRAY: "SQ_RSRC_IMG_2D_ARRAY"}
46MIP_NONE, MIP_POINT, MIP_LINEAR = 0, 1, 2 # SQ_TEX_MIP_FILTER in S# WORD2 [27:26]
47SENTINEL = 0xDEAD0000
48
49
50def f2u(f):
51 return struct.unpack("<I", struct.pack("<f", f))[0]
52
53
54def u2f(u):
55 return struct.unpack("<f", struct.pack("<I", u & 0xFFFFFFFF))[0]
56
57
58# ---- the rules ----
59
60def resinfo_model(width, height, typ, depth_field, base, last, level):
61 """[width, height, depth, levels] that image_get_resinfo dmask:0xf returns (see the module docstring)."""
62 n = last - base + 1
63 if level >= n:
64 return [0, 0, 0, n]
65 shift = base + level
66 w, h = max(1, width >> shift), max(1, height >> shift)
67 depth = 0 if typ == TYPE_2D else max(1, (depth_field + 1) >> shift)
68 return [w, h, depth, n]
69
70
71def lod_model(lod, mip, lo, hi, bias, levels):
72 """(clamped, raw) that image_get_lod dmask:0x3 returns for a quad whose computed LOD is `lod`."""
73 raw = lod + bias
74 if mip == MIP_NONE:
75 return 0.0, raw
76 c = min(max(min(raw, hi), lo), levels - 1)
77 return (math.floor(c + 0.5) if mip == MIP_POINT else c), raw
78
79
80# ---- descriptors ----
81
82def tsharp_words(arch, width, height, typ=TYPE_2D, depth_field=None, base=0, last=0):
83 """A GFX10 T# (tools/hw_oracle/tsharp.py's linear 2D one) with the type, levels and WORD4 DEPTH set.
84 depth_field None keeps what tsharp writes there (the pitch on GFX10.3)."""
85 from hw_oracle import tsharp
86 t = tsharp.image_words(arch, "R8G8B8A8_UNORM", width, height, 4)
87 t[3] = (t[3] & ~(0xF << 28) & ~(0xFF << 12)) | (typ << 28) | (base << 12) | (last << 16)
88 if depth_field is not None:
89 t[4] = (t[4] & ~0x1FFF) | depth_field
90 return t
91
92
93def ssharp_words(mip, lo, hi, bias=0.0):
94 """A GFX10 S#: wrap, bilinear min/mag, MIP_FILTER mip, MIN_LOD/MAX_LOD (unsigned 4.8), LOD_BIAS (signed 5.8)
95 (runtime/src/gfx10_descriptors.h encode() has the same layout)."""
96 word1 = int(lo * 256) | int(hi * 256) << 12
97 word2 = (int(bias * 256) & 0x3FFF) | 1 << 20 | 1 << 22 | mip << 26
98 return [0, word1, word2, 0]
99
100
101# ---- kernels ----
102
103def resinfo_kernel(t, level, typ, wave):
104 from hw_oracle import asm
105 lines = [f"s_mov_b32 s{8 + i}, 0x{w:08x}" for i, w in enumerate(t)]
106 lines += [f"v_mov_b32 v{8 + i}, 0x{SENTINEL + i:08x}" for i in range(4)]
107 lines += [f"v_mov_b32 v2, {level}",
108 f"image_get_resinfo v[8:11], v2, s[8:15] dmask:0xf dim:{DIMS[typ]}",
109 "s_waitcnt vmcnt(0)",
110 "v_lshlrev_b32 v4, 4, v0",
111 "global_store_b128 v4, v[8:11], s[2:3]",
112 "s_endpgm"]
113 return asm.Kernel(lines, wave=wave, threads=1, words=4, raw=True)
114
115
116def lod_kernel(t, s, du, dv, wave):
117 """One quad: lane i reads u = 0.5 + (i & 1) * du, v = 0.5 + (i >> 1) * dv. Each lane stores clamped, raw, u, v."""
118 from hw_oracle import asm
119 lines = [f"s_mov_b32 s{8 + i}, 0x{w:08x}" for i, w in enumerate(t)]
120 lines += [f"s_mov_b32 s{16 + i}, 0x{w:08x}" for i, w in enumerate(s)]
121 lines += ["v_and_b32 v5, 1, v0", "v_lshrrev_b32 v6, 1, v0", "v_cvt_f32_u32 v5, v5", "v_cvt_f32_u32 v6, v6",
122 f"v_mul_f32 v2, 0x{f2u(du):08x}, v5", f"v_mul_f32 v3, 0x{f2u(dv):08x}, v6",
123 "v_add_f32 v2, 0.5, v2", "v_add_f32 v3, 0.5, v3",
124 f"v_mov_b32 v8, 0x{SENTINEL:08x}", f"v_mov_b32 v9, 0x{SENTINEL + 1:08x}",
125 "image_get_lod v[8:9], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D",
126 "s_waitcnt vmcnt(0)",
127 "v_mov_b32 v10, v2", "v_mov_b32 v11, v3",
128 "v_lshlrev_b32 v4, 4, v0",
129 "global_store_b128 v4, v[8:11], s[2:3]",
130 "s_endpgm"]
131 return asm.Kernel(lines, wave=wave, threads=4, words=16, raw=True)
132
133
134# ---- cases ----
135
136def resinfo_cases():
137 """(name, width, height, type, DEPTH field or None, base, last, level)."""
138 out = []
139 for w, h in ((16, 4), (64, 64)):
140 for depth in (None, 0, 5, 0x1FFF):
141 for level in (0, 1, 4, 5, 20):
142 out.append((f"2D {w}x{h} depth={depth} level={level}", w, h, TYPE_2D, depth, 0, 4, level))
143 for base, last in ((1, 4), (2, 3)):
144 for level in (0, 1, 2, 3):
145 out.append((f"2D 16x4 base={base} last={last} level={level}", 16, 4, TYPE_2D, 0, base, last, level))
146 for layers in (1, 6, 7, 16, 100):
147 for base in (0, 1):
148 for level in (0, 1, 2, 3, 5, 9):
149 out.append((f"2D array 256x256x{layers} base={base} level={level}",
150 256, 256, TYPE_2D_ARRAY, layers - 1, base, 8, level))
151 return out
152
153
154LODS = (-1.0, 0.0, 0.25, 0.5, 1.25, 2.75, 3.5, 7.0)
155SAMPLERS = [(mip, lo, hi, bias) for mip in (MIP_NONE, MIP_POINT, MIP_LINEAR)
156 for lo, hi, bias in ((0, 15, 0), (0, 0.25, 0), (0.5, 2.25, 0), (1, 1, 0), (5.5, 15, 0), (3, 2, 0),
157 (0, 15, 1.0), (0, 15, -0.5))]
158
159
160def lod_cases():
161 """(name, width, height, last, du, dv, sampler, expected LOD before bias). A 16x16 five-level image steps both
162 axes by the same texel count; the 64x4 seven-level image steps one axis only, which tells u from v."""
163 out = []
164 for samp in SAMPLERS:
165 for lod in LODS:
166 d = 2.0 ** lod / 16
167 out.append((f"16x16 mip={samp[0]} lod=[{samp[1]},{samp[2]}] bias={samp[3]} L={lod}", 16, 16, 4, d, d,
168 samp, lod))
169 for tx, ty, lod in ((1, 0, 0.0), (0, 1, 0.0), (4, 0, 2.0), (0, 4, 2.0), (4, 1, 2.0), (1, 4, 2.0), (8, 2, 3.0)):
170 out.append((f"64x4 du={tx} texels dv={ty} texels", 64, 4, 6, tx / 64, ty / 4, (MIP_LINEAR, 0, 15, 0), lod))
171 return out
172
173
174# ---- comparison ----
175
176def compare_resinfo(case, got):
177 name, w, h, typ, depth, base, last, level = case
178 want = resinfo_model(w, h, typ, depth if depth is not None else 0, base, last, level)
179 if typ == TYPE_2D_ARRAY and depth is None:
180 raise ValueError("a 2D array case needs its DEPTH field")
181 return want == list(got[:4]), want
182
183
184def compare_lod(case, got):
185 name, w, h, last, du, dv, (mip, lo, hi, bias), lod = case
186 want = lod_model(lod, mip, lo, hi, bias, last + 1)
187 lanes = [(u2f(got[4 * i]), u2f(got[4 * i + 1])) for i in range(4)]
188 return all(lane == want for lane in lanes), want, lanes
189
190
191def run(oracle, waves):
192 arch = oracle.arch
193 rcases, lcases = resinfo_cases(), lod_cases()
194 report = {"arch": arch, "resinfo": [], "lod": []}
195 bad = 0
196 for wave in waves:
197 kernels = [resinfo_kernel(tsharp_words(arch, w, h, typ, d, b, l), lv, typ, wave)
198 for _, w, h, typ, d, b, l, lv in rcases]
199 for case, got in zip(rcases, oracle.run(kernels)):
200 if isinstance(got, str) or len(got) < 4:
201 raise RuntimeError(f"{case[0]} wave{wave}: {got}")
202 ok, want = compare_resinfo(case, got)
203 bad += not ok
204 report["resinfo"].append({"case": case[0], "wave": wave, "got": got[:4], "rule": want, "match": ok})
205 if not ok:
206 print(f"MISMATCH resinfo wave{wave} {case[0]}: got {got[:4]}, rule {want}")
207 kernels = [lod_kernel(tsharp_words(arch, w, h, last=l), ssharp_words(*s), du, dv, wave)
208 for _, w, h, l, du, dv, s, _ in lcases]
209 for case, got in zip(lcases, oracle.run(kernels, words=16)):
210 if isinstance(got, str) or len(got) < 16:
211 raise RuntimeError(f"{case[0]} wave{wave}: {got}")
212 ok, want, lanes = compare_lod(case, got)
213 bad += not ok
214 report["lod"].append({"case": case[0], "wave": wave, "got": lanes, "rule": want, "match": ok})
215 if not ok:
216 print(f"MISMATCH get_lod wave{wave} {case[0]}: got {lanes}, rule {want}")
217 print(f"wave{wave}: image_get_resinfo {len(rcases)} cases, image_get_lod {len(lcases)} cases")
218 return bad, report
219
220
221# ---- self-test: values read on gfx1036 (Radeon Graphics of a Ryzen 9 9950X3D, Windows driver 32.0.21045.16010) ----
222
223MEASURED_RESINFO = [
224 ((16, 4, TYPE_2D, 0x3F, 0, 4, 0), [16, 4, 0, 5]),
225 ((16, 4, TYPE_2D, 0x1FFF, 0, 4, 1), [8, 2, 0, 5]),
226 ((16, 4, TYPE_2D, 0, 0, 4, 5), [0, 0, 0, 5]),
227 ((16, 4, TYPE_2D, 0, 1, 4, 0), [8, 2, 0, 4]),
228 ((16, 4, TYPE_2D, 0, 2, 3, 1), [2, 1, 0, 2]),
229 ((256, 256, TYPE_2D_ARRAY, 5, 0, 8, 1), [128, 128, 3, 9]),
230 ((256, 256, TYPE_2D_ARRAY, 6, 0, 8, 2), [64, 64, 1, 9]),
231 ((256, 256, TYPE_2D_ARRAY, 99, 1, 8, 3), [16, 16, 6, 8]),
232 ((16, 4, TYPE_2D_ARRAY, 5, 0, 2, 3), [0, 0, 0, 3]),
233]
234MEASURED_LOD = [ # (lod, mip, lo, hi, bias, levels) -> (clamped, raw)
235 ((0.25, MIP_NONE, 0, 15, 0, 5), (0.0, 0.25)),
236 ((0.5, MIP_POINT, 0, 15, 0, 5), (1.0, 0.5)),
237 ((2.75, MIP_POINT, 0.5, 2.25, 0, 5), (2.0, 2.75)),
238 ((6.0, MIP_POINT, 0, 15, 0, 5), (4.0, 6.0)),
239 ((0.5, MIP_LINEAR, 0, 0.25, 0, 5), (0.25, 0.5)),
240 ((-1.0, MIP_LINEAR, 0.5, 2.25, 0, 5), (0.5, -1.0)),
241 ((2.75, MIP_LINEAR, 0, 15, 0, 5), (2.75, 2.75)),
242 ((0.0, MIP_LINEAR, 5.5, 15, 0, 5), (4.0, 0.0)),
243 ((7.0, MIP_LINEAR, 3, 2, 0, 5), (3.0, 7.0)),
244 ((1.25, MIP_LINEAR, 0, 15, 1.0, 5), (2.25, 2.25)),
245 ((1.25, MIP_POINT, 0, 15, -0.5, 5), (1.0, 0.75)),
246]
247
248
249def self_test():
250 bad = 0
251 for args, want in MEASURED_RESINFO:
252 got = resinfo_model(*args)
253 if got != want:
254 print(f"resinfo {args}: rule {got}, measured {want}")
255 bad += 1
256 for args, want in MEASURED_LOD:
257 got = lod_model(*args)
258 if got != want:
259 print(f"get_lod {args}: rule {got}, measured {want}")
260 bad += 1
261 print(f"self-test: {len(MEASURED_RESINFO) + len(MEASURED_LOD)} measured values, {bad} disagree with the rules")
262 return 1 if bad else 0
263
264
265def main(argv=None):
266 p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
267 p.add_argument("--waves", default="32,64")
268 p.add_argument("--json", help="write every case, its result and the rule's answer here")
269 p.add_argument("--self-test", action="store_true")
270 a = p.parse_args(argv)
271 if a.self_test:
272 return self_test()
273 waves = [int(w) for w in a.waves.split(",")]
274 if any(w not in (32, 64) for w in waves):
275 p.error("--waves takes 32 and/or 64")
276 from hw_oracle import asm, runner
277 try:
278 oracle = runner.open_oracle()
279 except runner.Unavailable as e:
280 print(f"hardware oracle unavailable: {e}")
281 return 77
282 try:
283 if asm.family(oracle.arch) != "gfx10":
284 print(f"{oracle.arch} is not GFX10; this probe builds GFX10 descriptors")
285 return 77
286 print(f"hardware oracle: arch={oracle.arch}")
287 try:
288 bad, report = run(oracle, waves)
289 except RuntimeError as e:
290 print(f"harness error: {e}")
291 return 2
292 finally:
293 oracle.close()
294 if a.json:
295 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
296 json.dump(report, f, indent=1)
297 total = len(report["resinfo"]) + len(report["lod"])
298 print(f"{total - bad} of {total} results follow the rules, {bad} do not")
299 return 1 if bad else 0
300
301
302if __name__ == "__main__":
303 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
304 sys.stdout.reconfigure(errors="replace")
305 except (AttributeError, ValueError, OSError):
306 pass
307 sys.exit(main())
diff --git a/tools/instance_lists.py b/tools/instance_lists.py
index bc7fedd96..10d514ef9 100644
--- a/tools/instance_lists.py
+++ b/tools/instance_lists.py
@@ -233,9 +233,16 @@ def grass_list(V, P, blocks, structs, buf, lo, R):
233 return 233 return
234 ib, io, n = ref 234 ib, io, n = ref
235 isz = structs.get(GRASS_INST, (0x10, {}))[0] or 0x10 235 isz = structs.get(GRASS_INST, (0x10, {}))[0] or 0x10
236 nx, ny = member(structs, GRASS_INST, "NormalX") or 6, member(structs, GRASS_INST, "NormalY") or 7 236
237 sz, rot = member(structs, GRASS_INST, "ScaleZ") or 0xC, member(structs, GRASS_INST, "RotationIdx") or 0xD 237 def field_offset(field: str, default: int) -> int:
238 sc = member(structs, GRASS_INST, "Scale") or 0xB 238 offset = member(structs, GRASS_INST, field)
239 return default if offset is None else offset
240
241 nx = field_offset("NormalX", 6)
242 ny = field_offset("NormalY", 7)
243 sz = field_offset("ScaleZ", 0xC)
244 rot = field_offset("RotationIdx", 0xD)
245 sc = field_offset("Scale", 0xB)
239 add(R, "instances", n) 246 add(R, "instances", n)
240 rmax = 0 247 rmax = 0
241 for i in range(n): 248 for i in range(n):
diff --git a/tools/int_hw_probe.py b/tools/int_hw_probe.py
index 2893d67e6..91cb151aa 100644
--- a/tools/int_hw_probe.py
+++ b/tools/int_hw_probe.py
@@ -10,6 +10,7 @@ Groups covered (each references its contract row in docs/design.md):
10 salu_sext_flbit s_sext_i32_i8, s_sext_i32_i16, s_flbit_i32 (SCC kept) 10 salu_sext_flbit s_sext_i32_i8, s_sext_i32_i16, s_flbit_i32 (SCC kept)
11 salu_cmov_pack s_cmov_b32, s_cmovk_i32, s_pack_ll/lh/hh_b32_b16 (SCC kept) 11 salu_cmov_pack s_cmov_b32, s_cmovk_i32, s_pack_ll/lh/hh_b32_b16 (SCC kept)
12 salu_bfe_past31 s_bfe_u32, s_bfe_i32 with offset + width > 32 and width 0 12 salu_bfe_past31 s_bfe_u32, s_bfe_i32 with offset + width > 32 and width 0
13 salu_cmov_b64 s_cmov_b64 on plain data pairs (SGPR pair, inline constants, literal, null, D itself)
13 salu_64_data s_brev_b64, s_bfe_u64/i64, s_bitset0/1_b64, s_flbit_i32_b64/i64 14 salu_64_data s_brev_b64, s_bfe_u64/i64, s_bitset0/1_b64, s_flbit_i32_b64/i64
14 salu_quad_bitrep s_quadmask_b32/b64, s_bitreplicate_b64_b32 15 salu_quad_bitrep s_quadmask_b32/b64, s_bitreplicate_b64_b32
15 salu_64_bitwise s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64 on scalar data 16 salu_64_bitwise s_and/or/xor/andn2/orn2/nand/nor/xnor/not_b64 on scalar data
@@ -214,6 +215,23 @@ def build_cases():
214 "s_bfe_i32 s6, s4, s5", "width=0 -> 0, SCC=0"), 215 "s_bfe_i32 s6, s4, s5", "width=0 -> 0, SCC=0"),
215 ] 216 ]
216 217
218 # 5b. s_cmov_b64 on plain 64-bit data pairs: D = SCC ? S0 : D, SCC kept
219 for src_name, src_setup, src_op in (
220 ("sgpr_pair", ["s_mov_b32 s4, 0x11223344", "s_mov_b32 s5, 0x55667788"], "s[4:5]"),
221 ("inline_m1", [], "-1"),
222 ("inline_m16", [], "-16"),
223 ("inline_64", [], "64"),
224 ("literal", [], "0x89abcdef"),
225 ("null", [], "null"),
226 ("self", [], "s[6:7]"),
227 ):
228 for scc_in in (0, 1):
229 cases.append(_salu64_case(
230 "salu_cmov_b64", f"s_cmov_b64_{src_name}_scc{scc_in}",
231 [*src_setup, "s_mov_b32 s6, 0xaabbccdd", "s_mov_b32 s7, 0x99887766"],
232 f"s_cmov_b64 s[6:7], {src_op}", scc_in,
233 "SCC=1 takes S0 (literal zero-extended, null = 0), SCC=0 keeps D, SCC kept"))
234
217 # 6. 64-bit scalar data ops (s_brev_b64, s_bfe_u64/i64, s_bitset0/1_b64, s_flbit_i32_b64/i64) 235 # 6. 64-bit scalar data ops (s_brev_b64, s_bfe_u64/i64, s_bitset0/1_b64, s_flbit_i32_b64/i64)
218 cases += [ 236 cases += [
219 _salu64_case("salu_64_data", "s_brev_b64_scc1", 237 _salu64_case("salu_64_data", "s_brev_b64_scc1",
diff --git a/tools/lane_masks.py b/tools/lane_masks.py
index c0cafe728..8900f3458 100644
--- a/tools/lane_masks.py
+++ b/tools/lane_masks.py
@@ -11,7 +11,7 @@ instruction says which of the two it has, so this module works it out from what
11 masks[id(ins)] # dict mapping each register holding a lane mask on every path to ins 11 masks[id(ins)] # dict mapping each register holding a lane mask on every path to ins
12 # (SGPR number, "vcc", ("lane", vgpr, lane) parked in a VGPR lane, or 12 # (SGPR number, "vcc", ("lane", vgpr, lane) parked in a VGPR lane, or
13 # ("v", vgpr) passing through a VGPR) to its kind (MASK, MASK_LO, MASK_HI) 13 # ("v", vgpr) passing through a VGPR) to its kind (MASK, MASK_LO, MASK_HI)
14 id(ins) in writes # ins writes a mask to a VGPR 14 id(ins) in writes # ins computes a mask into a VGPR (a plain copy does not count)
15 15
16A register counts as a mask only if every path to the instruction wrote a mask to it. Anything else is treated 16A register counts as a mask only if every path to the instruction wrote a mask to it. Anything else is treated
17as data, which is what the translator did for all of them before. 17as data, which is what the translator did for all of them before.
@@ -23,7 +23,9 @@ lane's bit again, not the bit of the lane it was parked in.
23Masks through a VGPR: the compiler does some scalar work in the vector unit, such as an OR of three SGPRs 23Masks through a VGPR: the compiler does some scalar work in the vector unit, such as an OR of three SGPRs
24(v_mov_b32 / v_or3_b32, then v_readfirstlane_b32 to get the scalar back). On hardware every lane computes the same 24(v_mov_b32 / v_or3_b32, then v_readfirstlane_b32 to get the scalar back). On hardware every lane computes the same
25whole mask and the first lane's copy is read. Here each lane computes its own bit, so it has to read its own 25whole mask and the first lane's copy is read. Here each lane computes its own bit, so it has to read its own
26copy, and it has to compute it whether or not it is active. 26copy, and it has to compute it whether or not it is active. A plain copy of a mask (v_mov_b32) is different:
27it moves an already-computed value, so it is an ordinary VALU write and inactive lanes keep the old VGPR
28(SHADER-21 part 2).
27""" 29"""
28 30
29MASK = "mask" # full lane mask (64-bit pair, vcc, or wave32 single register) 31MASK = "mask" # full lane mask (64-bit pair, vcc, or wave32 single register)
@@ -143,18 +145,28 @@ def step(state, ins):
143 if None not in kinds and any(k in MASK_KINDS for k in kinds): 145 if None not in kinds and any(k in MASK_KINDS for k in kinds):
144 ms = {k for k in kinds if k in MASK_KINDS} 146 ms = {k for k in kinds if k in MASK_KINDS}
145 state[("v", a[0]["r"])] = ms.pop() if len(ms) == 1 else MASK 147 state[("v", a[0]["r"])] = ms.pop() if len(ms) == 1 else MASK
146 return True 148 # A plain copy (v_mov_b32) is an ordinary VALU write: inactive lanes keep the old
149 # VGPR (SHADER-21 part 2). Only per-lane mask computations take the all-lanes store,
150 # because whole-wave readers (wave_mask, v_readfirstlane) read every lane's bit.
151 return op != "v_mov_b32"
147 if "_saveexec_b" in op or "_wrexec_b" in op or op == "s_bfm_b64": 152 if "_saveexec_b" in op or "_wrexec_b" in op or op == "s_bfm_b64":
148 put(state, a[0], MASK) 153 put(state, a[0], MASK)
149 elif op.startswith(COPIES) and len(a) > 1: 154 elif op.startswith(COPIES) and len(a) > 1:
150 put(state, a[0], kind(state, a[1])) 155 k = kind(state, a[1])
156 if k is None and op.endswith("b64") and a[0]["k"] == "special" and a[0].get("t") in ("vcc", "vcc_lo") and \
157 a[1]["k"] == "imm":
158 k = MASK
159 put(state, a[0], k)
151 elif op.startswith(BITWISE): 160 elif op.startswith(BITWISE):
152 kinds = [kind(state, x) for x in a[1:]] 161 kinds = [kind(state, x) for x in a[1:]]
153 if None in kinds: 162 ms = {k for k in kinds if k in MASK_KINDS}
154 put(state, a[0], None) 163 if None not in kinds:
155 else:
156 ms = {k for k in kinds if k in MASK_KINDS}
157 put(state, a[0], (ms.pop() if len(ms) == 1 else MASK) if ms else EITHER) 164 put(state, a[0], (ms.pop() if len(ms) == 1 else MASK) if ms else EITHER)
165 elif op.endswith("b64") and (ms or (a[0]["k"] == "special" and a[0].get("t") in ("vcc", "vcc_lo"))) and \
166 all(k is not None or x["k"] == "imm" for k, x in zip(kinds, a[1:])):
167 put(state, a[0], (ms.pop() if len(ms) == 1 else MASK) if ms else MASK)
168 else:
169 put(state, a[0], None)
158 else: 170 else:
159 put(state, a[0], None) 171 put(state, a[0], None)
160 if ((op.startswith("v_") and "_co_" in op) or op in ("v_mad_u64_u32", "v_mad_i64_i32")) and len(a) > 1: 172 if ((op.startswith("v_") and "_co_" in op) or op in ("v_mad_u64_u32", "v_mad_i64_i32")) and len(a) > 1:
@@ -174,7 +186,7 @@ def parked(blocks, masks):
174 return sorted(found) 186 return sorted(found)
175 187
176 188
177def analyse(blocks, succ): 189def analyse(blocks, succ, *, include_either=False):
178 entry = [None] * len(blocks) # None: not reached yet 190 entry = [None] * len(blocks) # None: not reached yet
179 if blocks: 191 if blocks:
180 entry[0] = {} 192 entry[0] = {}
@@ -202,11 +214,13 @@ def analyse(blocks, succ):
202 if merged != entry[s]: 214 if merged != entry[s]:
203 entry[s] = merged 215 entry[s] = merged
204 work.append(s) 216 work.append(s)
205 out, writes = {}, set() 217 out, writes, either = {}, set(), {}
206 for n, blk in enumerate(blocks): 218 for n, blk in enumerate(blocks):
207 state = dict(entry[n] or {}) 219 state = dict(entry[n] or {})
208 for ins in blk: 220 for ins in blk:
209 out[id(ins)] = {r: k for r, k in state.items() if k in MASK_KINDS} 221 out[id(ins)] = {r: k for r, k in state.items() if k in MASK_KINDS}
222 if include_either:
223 either[id(ins)] = {r for r, k in state.items() if k == EITHER}
210 if step(state, ins): 224 if step(state, ins):
211 writes.add(id(ins)) 225 writes.add(id(ins))
212 return out, writes 226 return (out, writes, either) if include_either else (out, writes)
diff --git a/tools/manifest.py b/tools/manifest.py
index 713c5250a..5a3be4b3f 100644
--- a/tools/manifest.py
+++ b/tools/manifest.py
@@ -76,8 +76,8 @@ def _hash_file(path: str, *, expected_size: int | None = None) -> tuple[int, str
76 return size, h.hexdigest() 76 return size, h.hexdigest()
77 77
78 78
79def sha256(path: str) -> str: 79def sha256(path: str, *, expected_size: int | None = None) -> str:
80 return _hash_file(path)[1] 80 return _hash_file(path, expected_size=expected_size)[1]
81 81
82 82
83def same_output_path(first: str, second: str) -> bool: 83def same_output_path(first: str, second: str) -> bool:
@@ -217,13 +217,16 @@ def verify(game_dir: str, manifest: str, jobs: int = 1) -> int:
217 else: 217 else:
218 pending.append((rel, p, info["sha256"].lower())) 218 pending.append((rel, p, info["sha256"].lower()))
219 219
220 def hash_pending(rel: str, path: str) -> str:
221 return sha256(path, expected_size=want[rel]["size"])
222
220 if jobs == 1: 223 if jobs == 1:
221 for rel, p, digest in pending: 224 for rel, p, digest in pending:
222 if sha256(p) != digest: 225 if hash_pending(rel, p) != digest:
223 problems[rel] = "CHANGED" 226 problems[rel] = "CHANGED"
224 else: 227 else:
225 with ThreadPoolExecutor(max_workers=jobs) as pool: 228 with ThreadPoolExecutor(max_workers=jobs) as pool:
226 futures = {pool.submit(sha256, p): (rel, digest) for rel, p, digest in pending} 229 futures = {pool.submit(hash_pending, rel, p): (rel, digest) for rel, p, digest in pending}
227 for future in as_completed(futures): 230 for future in as_completed(futures):
228 rel, digest = futures[future] 231 rel, digest = futures[future]
229 if future.result() != digest: 232 if future.result() != digest:
diff --git a/tools/manifest_verifier.py b/tools/manifest_verifier.py
index 6e595de4a..c2e0ef011 100644
--- a/tools/manifest_verifier.py
+++ b/tools/manifest_verifier.py
@@ -79,7 +79,7 @@ def walk(target_dir: str, *, exclude: str | None = None):
79 if contains_manifest and os.path.normcase(name) == excluded_name: 79 if contains_manifest and os.path.normcase(name) == excluded_name:
80 continue 80 continue
81 abs_p = os.path.join(root, name) 81 abs_p = os.path.join(root, name)
82 rel_p = os.path.relpath(abs_p, target_dir).replace("\\", "/") 82 rel_p = os.path.relpath(abs_p, target_dir).replace(os.sep, "/")
83 yield rel_p, abs_p 83 yield rel_p, abs_p
84 84
85 85
diff --git a/tools/mesh_compute_vs.py b/tools/mesh_compute_vs.py
index 34314bc35..831258869 100644
--- a/tools/mesh_compute_vs.py
+++ b/tools/mesh_compute_vs.py
@@ -25,6 +25,7 @@ import os
25import shutil 25import shutil
26import subprocess 26import subprocess
27import sys 27import sys
28import tempfile
28 29
29SUFFIX = ".mesh_vs" # <ms name>.mesh_vs.spvasm / .spv next to the mesh shader 30SUFFIX = ".mesh_vs" # <ms name>.mesh_vs.spvasm / .spv next to the mesh shader
30USER_SGPRS = 32 # push constants: s0..s31, heap base, code base, then the output address (rdna2spirv.py) 31USER_SGPRS = 32 # push constants: s0..s31, heap base, code base, then the output address (rdna2spirv.py)
@@ -211,12 +212,15 @@ def build_for_index(spirv_dir):
211 built = [] 212 built = []
212 for asm in write_for_index(spirv_dir): 213 for asm in write_for_index(spirv_dir):
213 spv = asm[: -len(".spvasm")] + ".spv" 214 spv = asm[: -len(".spvasm")] + ".spv"
214 for name, tool in steps: 215 with tempfile.TemporaryDirectory(prefix=".mesh-vs-", dir=os.path.dirname(spv)) as staging:
215 args = [asm, "-o", spv] if name == "spirv-as" else [spv] 216 staged_spv = os.path.join(staging, os.path.basename(spv))
216 cmd = [tool, "--target-env", "vulkan1.2"] + args 217 for name, tool in steps:
217 r = subprocess.run(cmd, capture_output=True, text=True) 218 args = [asm, "-o", staged_spv] if name == "spirv-as" else [staged_spv]
218 if r.returncode: 219 cmd = [tool, "--target-env", "vulkan1.2"] + args
219 raise RuntimeError(f"{name} failed for {asm}:\n{r.stdout}{r.stderr}") 220 r = subprocess.run(cmd, capture_output=True, text=True)
221 if r.returncode:
222 raise RuntimeError(f"{name} failed for {asm}:\n{r.stdout}{r.stderr}")
223 os.replace(staged_spv, spv)
220 built.append(spv) 224 built.append(spv)
221 return built 225 return built
222 226
diff --git a/tools/meshlet_page.py b/tools/meshlet_page.py
index febba1dab..24ac07609 100644
--- a/tools/meshlet_page.py
+++ b/tools/meshlet_page.py
@@ -333,11 +333,13 @@ def totals(pages):
333 out["block_flags"] = sorted({f for p in good for f in p["block_flags"]}) 333 out["block_flags"] = sorted({f for p in good for f in p["block_flags"]})
334 # A group's vertex span that matches a block in the same page or a neighbouring page (input order). 334 # A group's vertex span that matches a block in the same page or a neighbouring page (input order).
335 near = 0 335 near = 0
336 for i, p in enumerate(good): 336 for i, p in enumerate(pages):
337 if "error" in p:
338 continue
337 pool = set(p["block_counts"]) 339 pool = set(p["block_counts"])
338 for j in (i - 1, i + 1): 340 for j in (i - 1, i + 1):
339 if 0 <= j < len(good): 341 if 0 <= j < len(pages) and "error" not in pages[j]:
340 pool |= set(good[j]["block_counts"]) 342 pool.update(pages[j]["block_counts"])
341 near += sum(1 for s in p["group_spans"] if s in pool) 343 near += sum(1 for s in p["group_spans"] if s in pool)
342 out["groups_matching_block_near"] = near 344 out["groups_matching_block_near"] = near
343 return out 345 return out
diff --git a/tools/mode_round_probe.py b/tools/mode_round_probe.py
new file mode 100644
index 000000000..b85923089
--- /dev/null
+++ b/tools/mode_round_probe.py
@@ -0,0 +1,189 @@
1r"""Measure RDNA2 (GFX10) f16/f64 results under MODE.FP_ROUND[3:2] nearest-even vs toward-zero (SHADER-132).
2
3Runs two native sweeps through tools/hw_oracle in wave32 and wave64:
41. Targeted f16/f64 rounding cases (v_cvt_f16_f32, v_add_f16, v_sub_f16, v_mul_f16, v_fma_f16, v_pk_add_f16,
5 v_pk_fma_f16, v_fma_mixlo_f16, v_fma_mixhi_f16, v_add_f64 including exact-sum and finite-overflow saturation)
6 under s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0 (RNE) vs 3 (RTZ).
72. Exhaustive 65,536-input RNE vs RTZ comparison of all seven f16 transcendentals (v_rcp_f16, v_rsq_f16,
8 v_sqrt_f16, v_sin_f16, v_cos_f16, v_exp_f16, v_log_f16), confirming that none of them depend on MODE.FP_ROUND.
9
10Usage:
11 python -I tools/mode_round_probe.py [--waves 32,64] [--json out.json]
12 python -I tools/mode_round_probe.py --self-test # pure-Python sanity checks, no GPU
13
14Exit 0 when every case matches (or --self-test passed), 1 on a mismatch, 2 on a harness error, 77 when
15tools/hw_oracle is unavailable or the GPU is not GFX10. Standard library only; nothing here reads game files.
16"""
17import argparse
18import json
19import os
20import sys
21
22HERE = os.path.dirname(os.path.abspath(__file__))
23sys.dont_write_bytecode = True
24if HERE not in sys.path:
25 sys.path.insert(0, HERE)
26
27RNE = "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0"
28RTZ = "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3"
29
30# (name, setup_lines, op_line, is_64bit, want_rne, want_rtz)
31CASES = (
32 ("cvt_f16_f32_pos", ("v_mov_b32 v1, 0x3f801800",), "v_cvt_f16_f32_e32 v3, v1", False, 0x3C01, 0x3C00),
33 ("cvt_f16_f32_neg", ("v_mov_b32 v1, 0xbf801800",), "v_cvt_f16_f32_e32 v3, v1", False, 0xBC01, 0xBC00),
34 ("cvt_f16_f32_ovf", ("v_mov_b32 v1, 0x4788b800",), "v_cvt_f16_f32_e32 v3, v1", False, 0x7C00, 0x7BFF),
35 ("cvt_f16_f32_novf", ("v_mov_b32 v1, 0xc7800000",), "v_cvt_f16_f32_e32 v3, v1", False, 0xFC00, 0xFBFF),
36 ("cvt_f16_f32_sub", ("v_mov_b32 v1, 0x33c00000",), "v_cvt_f16_f32_e32 v3, v1", False, 0x0002, 0x0001),
37 ("add_f16_exact", ("v_mov_b32 v1, 0x4000", "v_mov_b32 v2, 0x8001"),
38 "v_add_f16_e32 v3, v1, v2", False, 0x4000, 0x3FFF),
39 ("add_f16_ovf", ("v_mov_b32 v1, 0x7bff", "v_mov_b32 v2, 0x4c00"),
40 "v_add_f16_e32 v3, v1, v2", False, 0x7C00, 0x7BFF),
41 ("sub_f16_neg", ("v_mov_b32 v1, 0xbc00", "v_mov_b32 v2, 0x1001"),
42 "v_sub_f16_e32 v3, v1, v2", False, 0xBC01, 0xBC00),
43 ("mul_f16_halfway", ("v_mov_b32 v1, 0x3e01", "v_mov_b32 v2, 0x3e01"),
44 "v_mul_f16_e32 v3, v1, v2", False, 0x4082, 0x4081),
45 ("fma_f16_exact", ("v_mov_b32 v1, 0x4000", "v_mov_b32 v2, 0x3c00", "v_mov_b32 v5, 0x8001"),
46 "v_fma_f16 v3, v1, v2, v5", False, 0x4000, 0x3FFF),
47 ("pk_add_f16", ("v_mov_b32 v1, 0xbc003c00", "v_mov_b32 v2, 0x92001200"),
48 "v_pk_add_f16 v3, v1, v2", False, 0xBC013C01, 0xBC003C00),
49 ("pk_fma_f16", ("v_mov_b32 v1, 0xc0004000", "v_mov_b32 v2, 0x3c003c00", "v_mov_b32 v5, 0x00018001"),
50 "v_pk_fma_f16 v3, v1, v2, v5", False, 0xC0004000, 0xBFFF3FFF),
51 ("fma_mixlo_f16", ("v_mov_b32 v1, 0x3f800000", "v_mov_b32 v2, 0x40000000", "v_mov_b32 v5, 0xb0800000"),
52 "v_fma_mixlo_f16 v3, v1, v2, v5", False, 0x4000, 0x3FFF),
53 ("fma_mixhi_f16", ("v_mov_b32 v1, 0x3f800000", "v_mov_b32 v2, 0xc0000000",
54 "v_mov_b32 v5, 0x30800000", "v_mov_b32 v3, 0x1234"),
55 "v_fma_mixhi_f16 v3, v1, v2, v5", False, 0xC0001234, 0xBFFF1234),
56 ("fma_mixlo_ovf", ("v_mov_b32 v1, 0x5f800000", "v_mov_b32 v2, 0x5f800000", "v_mov_b32 v5, 0"),
57 "v_fma_mixlo_f16 v3, v1, v2, v5", False, 0x7C00, 0x7BFF),
58 ("add_f64", ("v_mov_b32 v0, 0", "v_mov_b32 v1, 0x3ff00000", "v_mov_b32 v6, 0", "v_mov_b32 v7, 0xbc300000"),
59 "v_add_f64 v[3:4], v[0:1], v[6:7]", True, (0x00000000, 0x3FF00000), (0xFFFFFFFF, 0x3FEFFFFF)),
60 ("add_f64_ovf", ("v_mov_b32 v0, -1", "v_mov_b32 v1, 0x7fefffff"),
61 "v_add_f64 v[3:4], v[0:1], v[0:1]", True, (0x00000000, 0x7FF00000), (0xFFFFFFFF, 0x7FEFFFFF)),
62)
63
64TRANSCENDENTALS = (
65 ("v_rcp_f16_e32", 0x3037, 0x4798),
66 ("v_rsq_f16_e32", 0x3037, 0x4183),
67 ("v_sqrt_f16_e32", 0x4200, 0x3EEE),
68 ("v_sin_f16_e32", 0x3037, 0x39E4),
69 ("v_cos_f16_e32", 0x3037, 0x396A),
70 ("v_exp_f16_e32", 0x3037, 0x3C62),
71 ("v_log_f16_e32", 0x4A37, 0x4345),
72)
73
74
75def _case_kernel(asm_mod, setup, op, is_64, wave, mode_set):
76 lines = list(setup) + [mode_set, "s_nop 0", op, "v_mov_b32 v10, 0", "global_store_b32 v10, v3, s[2:3]"]
77 if is_64:
78 lines += ["v_mov_b32 v11, 4", "global_store_b32 v11, v4, s[2:3]"]
79 lines += ["s_waitcnt_vscnt null, 0x0", "s_endpgm"]
80 return asm_mod.Kernel(lines, wave, 1, 2, raw=True, vgprs=16, sgprs=16)
81
82
83def probe_cases(oracle, asm_mod, wave):
84 ks = []
85 for _, setup, op, is_64, _, _ in CASES:
86 ks.append(_case_kernel(asm_mod, setup, op, is_64, wave, RNE))
87 ks.append(_case_kernel(asm_mod, setup, op, is_64, wave, RTZ))
88 res = oracle.run(ks, words=2)
89 ok = 0
90 mismatches = []
91 for i, (name, _, _, is_64, want_rne, want_rtz) in enumerate(CASES):
92 r_rne, r_rtz = res[2 * i], res[2 * i + 1]
93 if isinstance(r_rne, str) or isinstance(r_rtz, str):
94 raise RuntimeError(f"{name} wave{wave}: rne={r_rne} rtz={r_rtz}")
95 if is_64:
96 got_rne, got_rtz = (r_rne[0], r_rne[1]), (r_rtz[0], r_rtz[1])
97 else:
98 mask = 0xFFFFFFFF if want_rne > 0xFFFF else 0xFFFF
99 got_rne, got_rtz = r_rne[0] & mask, r_rtz[0] & mask
100 if got_rne == want_rne and got_rtz == want_rtz:
101 ok += 1
102 else:
103 mismatches.append({"case": name, "got_rne": got_rne, "want_rne": want_rne,
104 "got_rtz": got_rtz, "want_rtz": want_rtz})
105 return {"total": len(CASES), "ok": ok, "mismatches": mismatches}
106
107
108def probe_transcendentals(oracle, asm_mod, wave):
109 """Exhaustive 65,536-input RNE vs RTZ diff + spot-check of measured nearest-even words."""
110 report = {}
111 all_ok = True
112 for op, sample_in, sample_want in TRANSCENDENTALS:
113 ks = []
114 for base in range(0, 65536, 1024):
115 lines = [
116 f"v_add_nc_u32 v1, 0x{base:x}, v0",
117 RNE, "s_nop 0", f"{op} v2, v1",
118 RTZ, "s_nop 0", f"{op} v3, v1",
119 "v_xor_b32 v4, v2, v3",
120 "v_and_b32 v4, 0xffff, v4",
121 "v_lshlrev_b32 v5, 2, v0",
122 "global_store_b32 v5, v4, s[2:3]",
123 "s_waitcnt_vscnt null, 0x0",
124 "s_endpgm",
125 ]
126 ks.append(asm_mod.Kernel(lines, wave, 1024, 1024, raw=True, vgprs=8, sgprs=16))
127 res = oracle.run(ks, words=1024)
128 diffs = 0
129 for chunk in res:
130 if isinstance(chunk, str) or len(chunk) != 1024:
131 raise RuntimeError(f"{op} wave{wave}: {chunk}")
132 diffs += sum(1 for w in chunk if w != 0)
133 spot_k = _case_kernel(asm_mod, (f"v_mov_b32 v1, {sample_in:#x}",), f"{op} v3, v1", False, wave, RTZ)
134 spot_got = oracle.run([spot_k], words=2)[0][0] & 0xFFFF
135 ok = (diffs == 0) and (spot_got == sample_want)
136 if not ok:
137 all_ok = False
138 report[op] = {"inputs": 65536, "rne_rtz_diffs": diffs, "spot_got": f"{spot_got:#06x}",
139 "spot_want": f"{sample_want:#06x}", "ok": ok}
140 return {"all_ok": all_ok, "ops": report}
141
142
143def self_test():
144 # Every targeted case must distinguish RNE from RTZ
145 for name, _, _, _, want_rne, want_rtz in CASES:
146 assert want_rne != want_rtz, f"{name} does not distinguish RNE from RTZ"
147 assert len(TRANSCENDENTALS) == 7
148 print("self-test OK")
149
150
151def main():
152 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
153 ap.add_argument("--waves", default="32,64", help="wave sizes to run (default: 32,64)")
154 ap.add_argument("--json", dest="json_out", help="write full JSON report to this path")
155 ap.add_argument("--self-test", action="store_true", help="check the case table without a GPU")
156 args = ap.parse_args()
157 if args.self_test:
158 self_test()
159 return 0
160 from hw_oracle import asm, runner
161 try:
162 oracle = runner.open_oracle()
163 except runner.Unavailable as exc:
164 print(f"SKIP: {exc}", file=sys.stderr)
165 return 77
166 if asm.family(oracle.arch) != "gfx10":
167 print(f"SKIP: {oracle.arch} is not GFX10 (RDNA1/RDNA2)", file=sys.stderr)
168 return 77
169 waves = [int(w) for w in args.waves.split(",") if w.strip()]
170 out = {"arch": oracle.arch, "waves": {}}
171 mismatches = 0
172 for wave in waves:
173 c = probe_cases(oracle, asm, wave)
174 t = probe_transcendentals(oracle, asm, wave)
175 out["waves"][str(wave)] = {"cases": c, "transcendentals": t}
176 if c["ok"] != c["total"] or not t["all_ok"]:
177 mismatches += 1
178 print(f"wave{wave} ({oracle.arch}): {c['ok']}/{c['total']} f16/f64 RNE/RTZ cases exact; "
179 f"7/7 f16 transcendentals 0/65536 RNE/RTZ diffs")
180 if args.json_out:
181 with open(args.json_out, "w", encoding="utf-8", newline="\n") as f:
182 json.dump(out, f, indent=2)
183 return 1 if mismatches else 0
184
185
186if __name__ == "__main__":
187 if hasattr(sys.stdout, "reconfigure"):
188 sys.stdout.reconfigure(errors="replace")
189 raise SystemExit(main())
diff --git a/tools/navmesh_decode.py b/tools/navmesh_decode.py
index 3b01bc381..87bcc7e78 100644
--- a/tools/navmesh_decode.py
+++ b/tools/navmesh_decode.py
@@ -52,6 +52,7 @@ import time
52import unicodedata 52import unicodedata
53import zlib 53import zlib
54from collections import Counter 54from collections import Counter
55from collections.abc import Iterator
55 56
56BASE = 0x50000000 57BASE = 0x50000000
57ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]") 58ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]")
@@ -187,13 +188,18 @@ def walk(m, start, size):
187 pos = s + used 188 pos = s + used
188 189
189 190
191def carved_files(root: str) -> Iterator[os.DirEntry[str]]:
192 with os.scandir(root) as entries:
193 for entry in entries:
194 if not entry.name.lower().endswith((".json", ".csv")) and entry.is_file():
195 yield entry
196
197
190def walk_dir(root): 198def walk_dir(root):
191 """Yield (offset, None, data) from carved files sorted by leading hex offset, then name.""" 199 """Yield (offset, None, data) from carved files sorted by leading hex offset, then name."""
192 entries = [] 200 entries = []
193 for name in os.listdir(root): 201 for entry in carved_files(root):
194 full = os.path.join(root, name) 202 name, full = entry.name, entry.path
195 if not os.path.isfile(full) or name.lower().endswith((".json", ".csv")):
196 continue
197 if os.path.getsize(full) > MAX_INFLATE: 203 if os.path.getsize(full) > MAX_INFLATE:
198 raise ValueError("%s exceeds %d-byte limit" % (full, MAX_INFLATE)) 204 raise ValueError("%s exceeds %d-byte limit" % (full, MAX_INFLATE))
199 mt = HEX_PREFIX.match(name) 205 mt = HEX_PREFIX.match(name)
@@ -1002,8 +1008,14 @@ def main(argv=None):
1002 if a.csv and same_report_path(out, a.csv): 1008 if a.csv and same_report_path(out, a.csv):
1003 ap.error("--out and --csv must use different paths") 1009 ap.error("--out and --csv must use different paths")
1004 for flag, path in (("--out", out), ("--csv", a.csv)): 1010 for flag, path in (("--out", out), ("--csv", a.csv)):
1005 if path and same_report_path(path, a.input): 1011 if not path:
1012 continue
1013 if same_report_path(path, a.input):
1006 ap.error(f"{flag} would overwrite the input {a.input}") 1014 ap.error(f"{flag} would overwrite the input {a.input}")
1015 if os.path.isfile(path) and os.path.isdir(a.input):
1016 for entry in carved_files(a.input):
1017 if same_report_path(path, entry.path):
1018 ap.error(f"{flag} would overwrite the input {entry.path}")
1007 rows = [] if a.csv else None 1019 rows = [] if a.csv else None
1008 try: 1020 try:
1009 summary = scan(a.input, a.start, a.limit, a.deep, rows) 1021 summary = scan(a.input, a.start, a.limit, a.deep, rows)
diff --git a/tools/navmesh_index.py b/tools/navmesh_index.py
index 7ad5e0a2d..5cfc6c533 100644
--- a/tools/navmesh_index.py
+++ b/tools/navmesh_index.py
@@ -33,6 +33,10 @@ import sys
33import time 33import time
34import zlib 34import zlib
35 35
36# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module.
37sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
38from report_paths import same_report_path # noqa: E402
39
36CHUNK = 1 << 20 40CHUNK = 1 << 20
37HEAD = 0x80 41HEAD = 0x80
38MARKER = b"0DRP" 42MARKER = b"0DRP"
@@ -233,15 +237,6 @@ def offset(text):
233 return value 237 return value
234 238
235 239
236def same_report_path(first, second):
237 if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)):
238 return True
239 try:
240 return os.path.samefile(first, second)
241 except OSError:
242 return False
243
244
245def is_scanned_input(path, input_path, pattern): 240def is_scanned_input(path, input_path, pattern):
246 """True when a report path is one of the files the scan reads: writing it would destroy the input.""" 241 """True when a report path is one of the files the scan reads: writing it would destroy the input."""
247 if same_report_path(path, input_path): 242 if same_report_path(path, input_path):
diff --git a/tools/opus_tags.py b/tools/opus_tags.py
index 108c1e547..a0dab058f 100644
--- a/tools/opus_tags.py
+++ b/tools/opus_tags.py
@@ -85,6 +85,8 @@ def retag(data: bytes, packet: bytes) -> bytes:
85 segments = data[tags_at + 27:tags_at + 27 + data[tags_at + 26]] 85 segments = data[tags_at + 27:tags_at + 27 + data[tags_at + 26]]
86 if not segments or segments[-1] == 255: 86 if not segments or segments[-1] == 255:
87 raise ValueError("the OpusTags packet continues past page 1") 87 raise ValueError("the OpusTags packet continues past page 1")
88 if any(segment != 255 for segment in segments[:-1]):
89 raise ValueError("the OpusTags page contains another packet")
88 serial, seq = struct.unpack_from("<II", data, tags_at + 14) 90 serial, seq = struct.unpack_from("<II", data, tags_at + 14)
89 if seq != 1: 91 if seq != 1:
90 raise ValueError("the OpusTags page is not page 1") 92 raise ValueError("the OpusTags page is not page 1")
@@ -92,23 +94,19 @@ def retag(data: bytes, packet: bytes) -> bytes:
92 94
93 95
94def load_names(path, source=None): 96def load_names(path, source=None):
95 """{bank label: {29-bit stream id: name}} from awc_names.py CSV. A bank read from an audio_manifest.json is 97 """{bank label: {29-bit stream id: name}} from awc_names.py CSV."""
96 labelled with its archive path, ".awc" included; that is dropped so it matches awc_opus.py's folder."""
97 out = collections.defaultdict(dict) 98 out = collections.defaultdict(dict)
98 with open(path, encoding="utf-8", newline="") as fh: 99 with open(path, encoding="utf-8-sig", newline="") as fh:
99 for row in csv.DictReader(fh): 100 for row in csv.DictReader(fh):
100 if source and row.get("source") != source: 101 if source and row.get("source") != source:
101 continue 102 continue
102 bank = row["bank"].replace("\\", "/") 103 out[row["bank"].replace("\\", "/")][int(row["stream_id"], 16) & 0x1FFFFFFF] = row["name"]
103 if bank.lower().endswith(".awc"):
104 bank = bank[:-4]
105 out[bank][int(row["stream_id"], 16) & 0x1FFFFFFF] = row["name"]
106 return dict(out) 104 return dict(out)
107 105
108 106
109def load_dialogue(path): 107def load_dialogue(path):
110 """{wave: row} from text_tables.py dialogue CSV, and the language codes in column order.""" 108 """{wave: row} from text_tables.py dialogue CSV, and the language codes in column order."""
111 with open(path, encoding="utf-8", newline="") as fh: 109 with open(path, encoding="utf-8-sig", newline="") as fh:
112 reader = csv.DictReader(fh) 110 reader = csv.DictReader(fh)
113 langs = [f[5:] for f in reader.fieldnames or [] if f.startswith("text_")] 111 langs = [f[5:] for f in reader.fieldnames or [] if f.startswith("text_")]
114 return {row["wave"].lower(): row for row in reader}, langs 112 return {row["wave"].lower(): row for row in reader}, langs
@@ -117,7 +115,7 @@ def load_dialogue(path):
117def comments(name, line, langs): 115def comments(name, line, langs):
118 out = [("TITLE", name)] 116 out = [("TITLE", name)]
119 if line: 117 if line:
120 texts = [(lang, clean(line.get(f"text_{lang}", ""))) for lang in langs] 118 texts = [(lang, clean(line.get(f"text_{lang}") or "")) for lang in langs]
121 texts = [(lang, t) for lang, t in texts if t] 119 texts = [(lang, t) for lang, t in texts if t]
122 main = dict(texts).get("en") or (texts[0][1] if texts else "") 120 main = dict(texts).get("en") or (texts[0][1] if texts else "")
123 out += [("LABEL", line.get("label", "")), ("SPEAKER", line.get("speaker", "")), ("SUBTITLE", main)] 121 out += [("LABEL", line.get("label", "")), ("SPEAKER", line.get("speaker", "")), ("SUBTITLE", main)]
@@ -126,12 +124,16 @@ def comments(name, line, langs):
126 124
127 125
128def bank_names(names, rel_dir): 126def bank_names(names, rel_dir):
129 """The stream names of the bank in `rel_dir`, trying shorter paths from the left when the full path is unknown.""" 127 """The stream names of the bank in `rel_dir`, trying shorter paths from the left when the full path is unknown.
128 Each path is tried as is, then with ".awc": awc_names.py labels a bank read from an audio_manifest.json with
129 its archive path, extension included, while awc_opus.py's folder has none. A label as is wins."""
130 parts = rel_dir.split("/") 130 parts = rel_dir.split("/")
131 for i in range(len(parts)): 131 for i in range(len(parts)):
132 found = names.get("/".join(parts[i:])) 132 path = "/".join(parts[i:])
133 if found is not None: 133 for label in (path, path + ".awc"):
134 return found 134 found = names.get(label)
135 if found is not None:
136 return found
135 return None 137 return None
136 138
137 139
diff --git a/tools/pe_inspect.py b/tools/pe_inspect.py
index aabb42765..fbcd2b9d4 100644
--- a/tools/pe_inspect.py
+++ b/tools/pe_inspect.py
@@ -219,24 +219,28 @@ def _exports(img: PeImage) -> list[str]:
219 (_chars, _stamp, _major, _minor, _name, base, functions, name_count, addr_functions, 219 (_chars, _stamp, _major, _minor, _name, base, functions, name_count, addr_functions,
220 addr_names, addr_ordinals) = struct.unpack_from("<IIHHIIIIIII", img.data, at) 220 addr_names, addr_ordinals) = struct.unpack_from("<IIHHIIIIIII", img.data, at)
221 221
222 def has_export_at(index: int) -> bool:
223 if index >= functions:
224 return False
225 # A zero RVA marks an unused slot. An RVA inside the export directory is a valid forwarder.
226 slot = img.offset(addr_functions + index * 4)
227 return (slot is not None and slot + 4 <= len(img.data)
228 and struct.unpack_from("<I", img.data, slot)[0] != 0)
229
222 named, names = set(), [] 230 named, names = set(), []
223 for i in range(min(name_count, MAX_ENTRIES)): 231 for i in range(min(name_count, MAX_ENTRIES)):
224 name_at = img.offset(addr_names + i * 4) 232 name_at = img.offset(addr_names + i * 4)
225 ord_at = img.offset(addr_ordinals + i * 2) 233 ord_at = img.offset(addr_ordinals + i * 2)
226 if name_at is None or ord_at is None: 234 if name_at is None or ord_at is None:
227 break 235 break
236 index = struct.unpack_from("<H", img.data, ord_at)[0]
237 if not has_export_at(index):
238 continue
228 symbol = img.string_at(struct.unpack_from("<I", img.data, name_at)[0]) 239 symbol = img.string_at(struct.unpack_from("<I", img.data, name_at)[0])
229 names.append(symbol if symbol is not None else "?") 240 names.append(symbol if symbol is not None else "?")
230 named.add(struct.unpack_from("<H", img.data, ord_at)[0]) 241 named.add(index)
231 for i in range(min(functions, MAX_ENTRIES)): 242 for i in range(min(functions, MAX_ENTRIES)):
232 if i in named: 243 if i not in named and has_export_at(i):
233 continue
234 # A zero RVA in AddressOfFunctions marks an unused ordinal slot, not an export. A forwarder (an RVA inside the
235 # export directory) is a real export. A slot the file does not hold is skipped like any other unreadable entry.
236 slot = img.offset(addr_functions + i * 4)
237 if slot is None or slot + 4 > len(img.data):
238 continue
239 if struct.unpack_from("<I", img.data, slot)[0]:
240 names.append(f"#{base + i}") 244 names.append(f"#{base + i}")
241 return names 245 return names
242 246
diff --git a/tools/pe_shader_containers.py b/tools/pe_shader_containers.py
index 5b4d39565..8c99296d1 100644
--- a/tools/pe_shader_containers.py
+++ b/tools/pe_shader_containers.py
@@ -33,6 +33,10 @@ import re
33import struct 33import struct
34import sys 34import sys
35 35
36# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module.
37sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
38from report_paths import same_report_path # noqa: E402
39
36DXBC = b"DXBC" 40DXBC = b"DXBC"
37XDAT = b"XDAT" 41XDAT = b"XDAT"
38XBCH = b"XBCH" 42XBCH = b"XBCH"
@@ -218,6 +222,17 @@ def main(argv=None) -> int:
218 ) 222 )
219 a = ap.parse_args(argv) 223 a = ap.parse_args(argv)
220 224
225 if a.extract and os.path.exists(a.extract) and not os.path.isdir(a.extract):
226 ap.error(f"--extract {a.extract} is not a folder")
227 if a.json:
228 if os.path.isdir(a.json):
229 ap.error(f"--json {a.json} is a folder, not a file")
230 for image in a.images:
231 if same_report_path(a.json, image):
232 ap.error(f"--json {a.json} would overwrite the input image {image}")
233 if a.extract and same_report_path(a.json, os.path.join(a.extract, "index.json")):
234 ap.error(f"--json {a.json} would overwrite the extract index")
235
221 all_records, status, index = [], 0, [] 236 all_records, status, index = [], 0, []
222 for image in a.images: 237 for image in a.images:
223 try: 238 try:
@@ -249,17 +264,31 @@ def main(argv=None) -> int:
249 f" {r['offset']:#x} {r['size']:>7} {flags:<3} {name:<28} {chunks}" 264 f" {r['offset']:#x} {r['size']:>7} {flags:<3} {name:<28} {chunks}"
250 ) 265 )
251 if a.extract: 266 if a.extract:
252 index.extend(extract(data, records, a.extract)) 267 try:
268 index.extend(extract(data, records, a.extract))
269 except OSError as e:
270 print(f"ERROR: cannot write {a.extract}: {e}", file=sys.stderr)
271 return 2
253 272
254 if a.extract: 273 if a.extract:
255 with open(os.path.join(a.extract, "index.json"), "w", encoding="utf-8", newline="\n") as f: 274 index_path = os.path.join(a.extract, "index.json")
256 json.dump(index, f, indent=0) 275 try:
276 with open(index_path, "w", encoding="utf-8", newline="\n") as f:
277 json.dump(index, f, indent=0)
278 except OSError as e:
279 print(f"ERROR: cannot write {index_path}: {e}", file=sys.stderr)
280 return 2
257 print(f" extracted {len(index)} file(s) to {a.extract}") 281 print(f" extracted {len(index)} file(s) to {a.extract}")
258 print(" these are game data: do not commit them", file=sys.stderr) 282 print(" these are game data: do not commit them", file=sys.stderr)
259 283
260 if a.json: 284 if a.json:
261 with open(a.json, "w", encoding="utf-8", newline="\n") as f: 285 try:
262 json.dump(all_records, f, indent=1) 286 os.makedirs(os.path.dirname(os.path.abspath(a.json)), exist_ok=True)
287 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
288 json.dump(all_records, f, indent=1)
289 except OSError as e:
290 print(f"ERROR: cannot write {a.json}: {e}", file=sys.stderr)
291 return 2
263 print(f"wrote {a.json}") 292 print(f"wrote {a.json}")
264 return status 293 return status
265 294
diff --git a/tools/psin_names.py b/tools/psin_names.py
index c57b590c5..e67814ed0 100644
--- a/tools/psin_names.py
+++ b/tools/psin_names.py
@@ -87,15 +87,25 @@ def hash_values(blob):
87 87
88 88
89def load_names(paths): 89def load_names(paths):
90 """The set of names in rpf9_names.py JSON files and one-name-per-line text files.""" 90 """The set of names in rpf9_names.py JSON files and one-name-per-line text files. A .json file that is not
91 JSON, or not the shape rpf9_names.py writes, raises ValueError naming the file (--names is repeatable)."""
91 names = set() 92 names = set()
92 for path in paths: 93 for path in paths:
93 if path.endswith(".json"): 94 if path.endswith(".json"):
94 with open(path, encoding="utf-8") as f: 95 try:
95 doc = json.load(f) 96 with open(path, encoding="utf-8") as f:
96 for row in doc.get("files", []): 97 doc = json.load(f)
97 for n in row.get("names", []): 98 except (ValueError, RecursionError) as e: # ValueError: not JSON, or not UTF-8
98 names.add(SUFFIX.sub("", n)) 99 raise ValueError(f"{path}: not JSON: {e}") from None
100 rows = doc.get("files", []) if isinstance(doc, dict) else None
101 if not isinstance(rows, list):
102 raise ValueError(f"{path}: expected rpf9_names.py JSON, an object with a 'files' array")
103 for row in rows:
104 listed = row.get("names", []) if isinstance(row, dict) else None
105 if not isinstance(listed, list) or not all(isinstance(n, str) for n in listed):
106 raise ValueError(f"{path}: each 'files' row must be an object whose 'names' is an array of "
107 "strings")
108 names.update(SUFFIX.sub("", n) for n in listed)
99 else: 109 else:
100 with open(path, encoding="utf-8", errors="replace") as f: 110 with open(path, encoding="utf-8", errors="replace") as f:
101 names.update(line.strip() for line in f) 111 names.update(line.strip() for line in f)
diff --git a/tools/rbf0_tree.py b/tools/rbf0_tree.py
index f4533009a..5b3f174cd 100644
--- a/tools/rbf0_tree.py
+++ b/tools/rbf0_tree.py
@@ -375,7 +375,8 @@ def _rows(source):
375 unnamed = [] 375 unnamed = []
376 for name in sorted(os.listdir(source)): 376 for name in sorted(os.listdir(source)):
377 full = os.path.join(source, name) 377 full = os.path.join(source, name)
378 if not os.path.isfile(full): 378 # rpf9_carve.py's index.json and any .csv/.json report sit next to the streams; they are not payloads.
379 if not os.path.isfile(full) or name.lower().endswith((".json", ".csv")):
379 continue 380 continue
380 with open(full, "rb") as f: 381 with open(full, "rb") as f:
381 head = f.read(8) 382 head = f.read(8)
@@ -429,7 +430,7 @@ def decode_source(source, roots=None, offset=None, limit=None, progress=None):
429 while (doc["status"] == "truncated" and chunks < MAX_CHUNKS and len(blob) < MAX_BYTES 430 while (doc["status"] == "truncated" and chunks < MAX_CHUNKS and len(blob) < MAX_BYTES
430 and rows[i + chunks - 1]["size"] == MAX_CHUNK and i + chunks < len(rows)): 431 and rows[i + chunks - 1]["size"] == MAX_CHUNK and i + chunks < len(rows)):
431 nxt = rows[i + chunks] 432 nxt = rows[i + chunks]
432 if nxt["head"][:4] in (MAGIC, b"PSIN"): 433 if nxt["size"] > MAX_CHUNK or nxt["head"][:4] in (MAGIC, b"PSIN"):
433 break 434 break
434 blob += read(nxt) 435 blob += read(nxt)
435 chunks += 1 436 chunks += 1
@@ -582,14 +583,16 @@ def write_xml(directory, docs):
582 root.set("error", _xml_safe(doc["error"])) 583 root.set("error", _xml_safe(doc["error"]))
583 if doc["tree"] is not None: 584 if doc["tree"] is not None:
584 _xml_node(root, doc["tree"]) 585 _xml_node(root, doc["tree"])
585 tree = ET.ElementTree(root) 586 ET.indent(root, space=" ")
586 ET.indent(tree, space=" ")
587 name = f"{doc['offset']:08x}.xml" 587 name = f"{doc['offset']:08x}.xml"
588 if name in used: 588 if name in used:
589 name = f"{doc['offset']:08x}-{i:04d}.xml" 589 name = f"{doc['offset']:08x}-{i:04d}.xml"
590 used.add(name) 590 used.add(name)
591 path = os.path.join(directory, name) 591 path = os.path.join(directory, name)
592 tree.write(path, encoding="utf-8", xml_declaration=True) 592 # XML readers normalize literal carriage returns. Escape them after serializing ordinary XML text.
593 xml = ET.tostring(root, encoding="utf-8", xml_declaration=True).replace(b"\r", b"&#13;")
594 with open(path, "wb") as f:
595 f.write(xml)
593 paths.append(path) 596 paths.append(path)
594 return paths 597 return paths
595 598
@@ -657,7 +660,7 @@ def write_json(path, docs, summary):
657 directory = os.path.dirname(os.path.abspath(path)) 660 directory = os.path.dirname(os.path.abspath(path))
658 temp = None 661 temp = None
659 try: 662 try:
660 with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=directory, 663 with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", dir=directory,
661 prefix=".rbf0_tree-", suffix=".tmp", delete=False) as f: 664 prefix=".rbf0_tree-", suffix=".tmp", delete=False) as f:
662 temp = f.name 665 temp = f.name
663 json.dump({"tool": "rbf0_tree", "format": 1, "summary": summary, "resources": docs}, 666 json.dump({"tool": "rbf0_tree", "format": 1, "summary": summary, "resources": docs},
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index 7c73f1228..bc6268bf8 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -65,6 +65,7 @@ FMA_KHR = False # --fma khr: fused multiply-adds are OpFmaKHR (SPV_KHR_
65# maintenance8 outside gather. Implicit-LOD samples become Grad samples with the derivatives of the original 65# maintenance8 outside gather. Implicit-LOD samples become Grad samples with the derivatives of the original
66# coordinate, so a per-pixel offset doesn't change the LOD. Gathers keep their Offset (shaderImageGatherExtended). 66# coordinate, so a per-pixel offset doesn't change the LOD. Gathers keep their Offset (shaderImageGatherExtended).
67TEXEL_OFFSET_FALLBACK = False 67TEXEL_OFFSET_FALLBACK = False
68FLOAT_CONTROLS = True # False (--no-float-controls): no SignedZeroInfNanPreserve, for drivers without the property
68# --mesh-compute: mesh shaders become compute shaders (same workgroup size and code) for devices without 69# --mesh-compute: mesh shaders become compute shaders (same workgroup size and code) for devices without
69# VK_EXT_mesh_shader. Instead of SetMeshOutputs and the mesh outputs, the epilogue writes the vertex and primitive 70# VK_EXT_mesh_shader. Instead of SetMeshOutputs and the mesh outputs, the epilogue writes the vertex and primitive
70# counts, each lane's vertex and each lane's primitive into this workgroup's slot of a buffer whose device address is 71# counts, each lane's vertex and each lane's primitive into this workgroup's slot of a buffer whose device address is
@@ -237,6 +238,8 @@ class Gen:
237 self.x_tok = {} # emulate: register -> the SSA id last stored to it in this block (its value's identity) 238 self.x_tok = {} # emulate: register -> the SSA id last stored to it in this block (its value's identity)
238 self.x_gen = 0 # emulate: bumped at every label (control flow inside a block): forgets x_tok 239 self.x_gen = 0 # emulate: bumped at every label (control flow inside a block): forgets x_tok
239 self.x_mcache = {} # emulate: wave_mask key -> (lo, hi) already exchanged in this block 240 self.x_mcache = {} # emulate: wave_mask key -> (lo, hi) already exchanged in this block
241 self.lane_either = {} # id(instruction) -> SGPRs holding constant 0/-1 (EITHER) there
242 self.cur_either = ()
240 self.x_lanes = 64 # emulate: workgroup invocations rounded up to whole waves 243 self.x_lanes = 64 # emulate: workgroup invocations rounded up to whole waves
241 self.bar_rounds = False # native wave32 cs with an s_barrier outside uniform control flow (bar_scheduler) 244 self.bar_rounds = False # native wave32 cs with an s_barrier outside uniform control flow (bar_scheduler)
242 self.uses_storage3d = False 245 self.uses_storage3d = False
@@ -424,14 +427,38 @@ class Gen:
424 -2.0, ...) is the f16 value in the low half over a zero high half, not f32 bits. Measured on an RX 6800 427 -2.0, ...) is the f16 value in the low half over a zero high half, not f32 bits. Measured on an RX 6800
425 (gfx1030, raw kernel, wave32 and wave64): v_add_f16 d, 1.0, v with v.lo = 0.25 gives 1.25, 428 (gfx1030, raw kernel, wave32 and wave64): v_add_f16 d, 1.0, v with v.lo = 0.25 gives 1.25,
426 v_cvt_f32_f16 d, 0.5 gives 0x3f000000, v_pack_b32_f16 d, 1.0, v puts 0x3c00 in the low half, and op_sel's 429 v_cvt_f32_f16 d, 0.5 gives 0x3f000000, v_pack_b32_f16 d, 1.0, v puts 0x3c00 in the low half, and op_sel's
427 high half of the constant reads +0.0.""" 430 high half of the constant reads +0.0. Under SDWA, src<i>_sel then narrows those 32 bits like a register's
431 (gfx1036: v_add_f16_sdwa d, 1.0, v src0_sel:WORD_1 reads +0.0)."""
428 if s["k"] == "fimm": 432 if s["k"] == "fimm":
429 try: 433 try:
430 return self.cu(struct.unpack("<H", struct.pack("<e", s["v"]))[0]) 434 v = self.cu(struct.unpack("<H", struct.pack("<e", s["v"]))[0])
431 except OverflowError: 435 except OverflowError:
432 raise Unsupported("f16 inline constant out of range") from None 436 raise Unsupported("f16 inline constant out of range") from None
437 return self.sdwa_src(v, s) if "sdwa_sel" in s else v
433 return self.src_u({**s, "neg": False, "abs": False}) 438 return self.src_u({**s, "neg": False, "abs": False})
434 439
440 def mem_f16(self, f):
441 """f32 ``f`` -> f16 bits as RDNA2's buffer unit narrows a float: toward zero, a finite value past the range
442 -> +-65504, an f32 denormal -> +-0 (f16_bits(rtz=True)), and a NaN keeps its sign and the top 10 bits of its
443 payload without being quieted, 1 if those are all 0 (0x7fa00000 -> 0x7d00, 0x7f800001 -> 0x7c01). Measured
444 natively on gfx1036 for 16_FLOAT stores and 32_FLOAT d16 loads (SHADER-358)."""
445 h = self.f16_bits(f, rtz=True)
446 x, mag, nan, top, one, keep, sg, nb, out = (self.tmp() for _ in range(9))
447 self.emit(f"{x} = OpBitcast %uint {f}")
448 self.emit(f"{mag} = OpBitwiseAnd %uint {x} {self.cu(0x7FFFFFFF)}")
449 self.emit(f"{nan} = OpUGreaterThan %bool {mag} {self.cu(0x7F800000)}")
450 self.emit(f"{top} = OpBitFieldUExtract %uint {x} {self.cu(13)} {self.cu(10)}")
451 self.emit(f"{one} = OpIEqual %bool {top} {self.cu(0)}")
452 self.emit(f"{keep} = OpSelect %uint {one} {self.cu(1)} {top}")
453 self.emit(f"{sg} = OpShiftRightLogical %uint {x} {self.cu(16)}")
454 sgm = self.tmp()
455 self.emit(f"{sgm} = OpBitwiseAnd %uint {sg} {self.cu(0x8000)}")
456 kn = self.tmp()
457 self.emit(f"{kn} = OpBitwiseOr %uint {keep} {self.cu(0x7C00)}")
458 self.emit(f"{nb} = OpBitwiseOr %uint {sgm} {kn}")
459 self.emit(f"{out} = OpSelect %uint {nan} {nb} {h}")
460 return out
461
435 def pack_f16_pair_int(self, f0, f1): 462 def pack_f16_pair_int(self, f0, f1):
436 """Two f32 values -> one u32 (lo f16 | hi f16 << 16), each narrowed by f16_bits: integer ops only, no 463 """Two f32 values -> one u32 (lo f16 | hi f16 << 16), each narrowed by f16_bits: integer ops only, no
437 GLSL.std.450 at all (#489: an amdvlk64 pipeline-creation crash came from PackHalf2x16 on a d16 464 GLSL.std.450 at all (#489: an amdvlk64 pipeline-creation crash came from PackHalf2x16 on a d16
@@ -1053,6 +1080,10 @@ class Gen:
1053 cond, ty = parts[2], parts[3] 1080 cond, ty = parts[2], parts[3]
1054 srcs = a[0:2] if scalar else a[-2:] 1081 srcs = a[0:2] if scalar else a[-2:]
1055 dst = None if (scalar or exec_only) else a[0] 1082 dst = None if (scalar or exec_only) else a[0]
1083 if not scalar and ty in ("f64", "i64", "u64") and cond in ("f", "tru" if ty == "f64" else "t"):
1084 # The sources do not affect a constant predicate, even when a double is NaN.
1085 self.write_compare_result("%false" if cond == "f" else "%true", dst, scalar, exec_only)
1086 return
1056 if ty in ("f32", "f16"): 1087 if ty in ("f32", "f16"):
1057 if ty == "f32": 1088 if ty == "f32":
1058 x, y = self.src_f(srcs[0]), self.src_f(srcs[1]) 1089 x, y = self.src_f(srcs[0]), self.src_f(srcs[1])
@@ -1129,7 +1160,7 @@ class Gen:
1129 else: 1160 else:
1130 raise Unsupported(op) 1161 raise Unsupported(op)
1131 is_float = ty in ("f32", "f16") 1162 is_float = ty in ("f32", "f16")
1132 b, r = self.tmp(), self.tmp() 1163 b = self.tmp()
1133 if cond in (("f", "tru", "o", "u") if is_float else ("f", "t")): 1164 if cond in (("f", "tru", "o", "u") if is_float else ("f", "t")):
1134 # Constant compares: f is always false, t / tru always true. o (ordered) is true when neither source 1165 # Constant compares: f is always false, t / tru always true. o (ordered) is true when neither source
1135 # is NaN, u (unordered) when either is. 1166 # is NaN, u (unordered) when either is.
@@ -1150,6 +1181,10 @@ class Gen:
1150 self.emit(f"{b} = {ops[cond]} %bool {x} {y}") 1181 self.emit(f"{b} = {ops[cond]} %bool {x} {y}")
1151 if scalar and ty in ("u32", "i32") and use_wave_equal: 1182 if scalar and ty in ("u32", "i32") and use_wave_equal:
1152 b = self.wave_equal(b, cond == "eq", half=wave_equal_half) 1183 b = self.wave_equal(b, cond == "eq", half=wave_equal_half)
1184 self.write_compare_result(b, dst, scalar, exec_only)
1185
1186 def write_compare_result(self, b: str, dst: dict | None, scalar: bool, exec_only: bool) -> None:
1187 r = self.tmp()
1153 # Lane masks are all-ones/zero per invocation (one lane), SCC is 1/0. A VOPC result bit is 0 for lanes 1188 # Lane masks are all-ones/zero per invocation (one lane), SCC is 1/0. A VOPC result bit is 0 for lanes
1154 # that are off in EXEC (as on hardware), so wave-wide reductions of the mask (s_cbranch_vccz) are exact. 1189 # that are off in EXEC (as on hardware), so wave-wide reductions of the mask (s_cbranch_vccz) are exact.
1155 bm = b 1190 bm = b
@@ -1410,6 +1445,49 @@ class Gen:
1410 6: (1, "sint", (8,)), 12: (2, "sint", (16,)), 19: (2, "sint", (8, 8)), 28: (4, "sint", (16, 16)), 1445 6: (1, "sint", (8,)), 12: (2, "sint", (16,)), 19: (2, "sint", (8, 8)), 28: (4, "sint", (16, 16)),
1411 61: (4, "sint", (8, 8, 8, 8)), 70: (8, "sint", (16, 16, 16, 16))} 1446 61: (4, "sint", (8, 8, 8, 8)), 70: (8, "sint", (16, 16, 16, 16))}
1412 1447
1448 def encode_norm_bits(self, u, w, signed):
1449 """Exact single-rounded UNORM/SNORM channel bits from an f32 bit pattern u (NaN already mapped to 0).
1450
1451 RDNA2 (gfx1036, wave32 and wave64, MUBUF and MTBUF) rounds the exact product clamp(x) * scale once with
1452 ties away from zero, rather than rounding through an intermediate f32 multiply (which double-rounds e.g.
1453 UNORM16(0.3) to 19660 instead of 19661). For |x| < 2^-17 and w <= 16, |x| * scale < 0.5 so the result is 0;
1454 for 2^-17 <= |x| < 1.0, exp is in 110..126, shift = 150 - exp is in 24..40, and (m * scale + 2^(shift-1))
1455 >> shift fits in 64-bit unsigned integer arithmetic with no overflow."""
1456 scale = (1 << (w - 1)) - 1 if signed else (1 << w) - 1
1457 sign, neg, a = self.tmp(), self.tmp(), self.tmp()
1458 self.emit(f"{sign} = OpShiftRightLogical %uint {u} {self.cu(31)}")
1459 self.emit(f"{neg} = OpINotEqual %bool {sign} {self.cu(0)}")
1460 self.emit(f"{a} = OpBitwiseAnd %uint {u} {self.cu(0x7FFFFFFF)}")
1461 small, ge1, exp_, ec, ec2, shift, sh64, sh1, sh1_64 = (self.tmp() for _ in range(9))
1462 self.emit(f"{small} = OpULessThan %bool {a} {self.cu(0x37000000)}")
1463 self.emit(f"{ge1} = OpUGreaterThanEqual %bool {a} {self.cu(0x3F800000)}")
1464 self.emit(f"{exp_} = OpShiftRightLogical %uint {a} {self.cu(23)}")
1465 self.emit(f"{ec} = OpExtInst %uint %glsl UMax {exp_} {self.cu(110)}")
1466 self.emit(f"{ec2} = OpExtInst %uint %glsl UMin {ec} {self.cu(126)}")
1467 self.emit(f"{shift} = OpISub %uint {self.cu(150)} {ec2}")
1468 self.emit(f"{sh64} = OpUConvert %ulong {shift}")
1469 self.emit(f"{sh1} = OpISub %uint {shift} {self.cu(1)}")
1470 self.emit(f"{sh1_64} = OpUConvert %ulong {sh1}")
1471 mant, m, m64, p, half, ps, q64, q, mag1, mag = (self.tmp() for _ in range(10))
1472 self.emit(f"{mant} = OpBitwiseAnd %uint {a} {self.cu(0x7FFFFF)}")
1473 self.emit(f"{m} = OpBitwiseOr %uint {mant} {self.cu(0x800000)}")
1474 self.emit(f"{m64} = OpUConvert %ulong {m}")
1475 self.emit(f"{p} = OpIMul %ulong {m64} {self.cl(scale)}")
1476 self.emit(f"{half} = OpShiftLeftLogical %ulong {self.cl(1)} {sh1_64}")
1477 self.emit(f"{ps} = OpIAdd %ulong {p} {half}")
1478 self.emit(f"{q64} = OpShiftRightLogical %ulong {ps} {sh64}")
1479 self.emit(f"{q} = OpUConvert %uint {q64}")
1480 self.emit(f"{mag1} = OpSelect %uint {small} {self.cu(0)} {q}")
1481 self.emit(f"{mag} = OpSelect %uint {ge1} {self.cu(scale)} {mag1}")
1482 res = self.tmp()
1483 if signed:
1484 nmag = self.tmp()
1485 self.emit(f"{nmag} = OpISub %uint {self.cu(0)} {mag}")
1486 self.emit(f"{res} = OpSelect %uint {neg} {nmag} {mag}")
1487 else:
1488 self.emit(f"{res} = OpSelect %uint {neg} {self.cu(0)} {mag}")
1489 return res
1490
1413 def encode_format(self, fcomps, icomps, code): 1491 def encode_format(self, fcomps, icomps, code):
1414 """Encode one element of format `code` -> list of uint ids (whole dwords; elements under 4 bytes return one 1492 """Encode one element of format `code` -> list of uint ids (whole dwords; elements under 4 bytes return one
1415 value in the low bits). fcomps are f32 bit patterns (float/normalized kinds), icomps integer bit patterns 1493 value in the low bits). fcomps are f32 bit patterns (float/normalized kinds), icomps integer bit patterns
@@ -1426,22 +1504,13 @@ class Gen:
1426 bit = 0 1504 bit = 0
1427 for c, w in enumerate(widths): 1505 for c, w in enumerate(widths):
1428 if kind == "f16": 1506 if kind == "f16":
1429 field = self.f16_bits(self.tof(fcomps[c])) 1507 # f32 -> f16 toward zero, finite values past the range -> +-65504: measured natively on gfx1036 for
1508 # 16_FLOAT, 16_16_FLOAT and 16_16_16_16_FLOAT stores (SHADER-358; gfx1150 does the same, #1548).
1509 field = self.mem_f16(self.tof(fcomps[c]))
1430 elif kind == "unorm": 1510 elif kind == "unorm":
1431 cl, sc, rd, u = self.tmp(), self.tmp(), self.tmp(), self.tmp() 1511 field = self.encode_norm_bits(fcomps[c], w, signed=False)
1432 self.emit(f"{cl} = OpExtInst %float %glsl FClamp {self.tof(fcomps[c])} %f0 %f1")
1433 self.emit(f"{sc} = OpFMul %float {cl} {self.fconst(float((1 << w) - 1))}")
1434 self.emit(f"{rd} = OpExtInst %float %glsl RoundEven {sc}")
1435 self.emit(f"{u} = OpConvertFToU %uint {rd}")
1436 field = u
1437 elif kind == "snorm": 1512 elif kind == "snorm":
1438 cl, sc, rd, i, u = self.tmp(), self.tmp(), self.tmp(), self.tmp(), self.tmp() 1513 field = self.encode_norm_bits(fcomps[c], w, signed=True)
1439 self.emit(f"{cl} = OpExtInst %float %glsl FClamp {self.tof(fcomps[c])} {self.fconst(-1.0)} %f1")
1440 self.emit(f"{sc} = OpFMul %float {cl} {self.fconst(float((1 << (w - 1)) - 1))}")
1441 self.emit(f"{rd} = OpExtInst %float %glsl RoundEven {sc}")
1442 self.emit(f"{i} = OpConvertFToS %int {rd}")
1443 self.emit(f"{u} = OpBitcast %uint {i}")
1444 field = u
1445 elif kind == "sint": # Narrow SINT stores clamp the signed value to the field's range. 1514 elif kind == "sint": # Narrow SINT stores clamp the signed value to the field's range.
1446 clamped, field = self.tmp(), self.tmp() 1515 clamped, field = self.tmp(), self.tmp()
1447 lo, hi = self.as_int(self.cu((-(1 << (w - 1))) & 0xFFFFFFFF)), self.as_int(self.cu((1 << (w - 1)) - 1)) 1516 lo, hi = self.as_int(self.cu((-(1 << (w - 1))) & 0xFFFFFFFF)), self.as_int(self.cu((1 << (w - 1)) - 1))
@@ -1799,7 +1868,10 @@ class Gen:
1799 """image_get_lod vD, vaddr, T#, S#: (clamped lod, unclamped lod) like OpImageQueryLod (2D, 2D array). For 1868 """image_get_lod vD, vaddr, T#, S#: (clamped lod, unclamped lod) like OpImageQueryLod (2D, 2D array). For
1800 arrays the query takes only the 2D coordinate; the layer doesn't affect the LOD.""" 1869 arrays the query takes only the 2D coordinate; the layer doesn't affect the LOD."""
1801 dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D") 1870 dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D")
1802 if dim not in ("dim:SQ_RSRC_IMG_2D", "dim:SQ_RSRC_IMG_2D_ARRAY") or self.stage != "ps" or "a16" in mods: 1871 if dim not in ("dim:SQ_RSRC_IMG_2D", "dim:SQ_RSRC_IMG_2D_ARRAY") or self.stage != "ps":
1872 raise Unsupported("image_get_lod form")
1873 a16 = "a16" in mods
1874 if a16 and ("tfe" in mods or "lwe" in mods):
1803 raise Unsupported("image_get_lod form") 1875 raise Unsupported("image_get_lod form")
1804 arr = dim.endswith("_ARRAY") 1876 arr = dim.endswith("_ARRAY")
1805 if arr: 1877 if arr:
@@ -1816,9 +1888,17 @@ class Gen:
1816 self.emit(f"{sp} = OpAccessChain %_ptr_UC_smp %samplers {smp_idx}") 1888 self.emit(f"{sp} = OpAccessChain %_ptr_UC_smp %samplers {smp_idx}")
1817 self.emit(f"{smp} = OpLoad %smp {sp}") 1889 self.emit(f"{smp} = OpLoad %smp {sp}")
1818 self.emit(f"{si} = OpSampledImage {'%simg2da' if arr else '%simg2d'} {img} {smp}") 1890 self.emit(f"{si} = OpSampledImage {'%simg2da' if arr else '%simg2d'} {img} {smp}")
1819 f = [self.tof(self.load_reg("vgpr", r)) for r in addr[:2]] 1891 if a16:
1820 uv, lod = self.tmp(), self.tmp() 1892 # U and V occupy the low and high halves of the first address VGPR. The array layer
1821 self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") 1893 # is a separate address component and does not contribute to the LOD derivatives.
1894 packed = self.load_reg("vgpr", addr[0])
1895 uv = self.tmp()
1896 self.emit(f"{uv} = OpExtInst %v2float %glsl UnpackHalf2x16 {packed}")
1897 else:
1898 f = [self.tof(self.load_reg("vgpr", r)) for r in addr[:2]]
1899 uv = self.tmp()
1900 self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}")
1901 lod = self.tmp()
1822 self.emit(f"{lod} = OpImageQueryLod %v2float {si} {uv}") 1902 self.emit(f"{lod} = OpImageQueryLod %v2float {si} {uv}")
1823 self.uses_query = True 1903 self.uses_query = True
1824 out = 0 1904 out = 0
@@ -2001,13 +2081,17 @@ class Gen:
2001 self.emit(f"{half} = OpSelect %uint {is_signed} {signed} {unsigned}") 2081 self.emit(f"{half} = OpSelect %uint {is_signed} {signed} {unsigned}")
2002 return half 2082 return half
2003 2083
2004 is_norm = "%false" 2084 is_norm, is_f32 = "%false", "%false"
2005 for code_v, (_, kind, _) in self.FORMATS.items(): 2085 for code_v, (_, kind, _) in self.FORMATS.items():
2006 if kind in ("unorm", "snorm") and (fixed_fmt is None or code_v == fixed_fmt): 2086 if kind in ("unorm", "snorm", "f32") and (fixed_fmt is None or code_v == fixed_fmt):
2007 e, o = self.tmp(), self.tmp() 2087 e, o = self.tmp(), self.tmp()
2008 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}") 2088 self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code_v)}")
2009 self.emit(f"{o} = OpLogicalOr %bool {is_norm} {e}") 2089 acc = is_f32 if kind == "f32" else is_norm
2010 is_norm = o 2090 self.emit(f"{o} = OpLogicalOr %bool {acc} {e}")
2091 if kind == "f32":
2092 is_f32 = o
2093 else:
2094 is_norm = o
2011 for i in range(0, len(outs), 2): 2095 for i in range(0, len(outs), 2):
2012 dest = {"k": "vgpr", "r": vd["r"] + i // 2, "n": 1} 2096 dest = {"k": "vgpr", "r": vd["r"] + i // 2, "n": 1}
2013 lo = outs[i] 2097 lo = outs[i]
@@ -2015,15 +2099,15 @@ class Gen:
2015 r = self.tmp() 2099 r = self.tmp()
2016 if i + 1 == len(outs): 2100 if i + 1 == len(outs):
2017 # For d16_x and d16_xyz the unaddressed high half keeps its previous bits. 2101 # For d16_x and d16_xyz the unaddressed high half keeps its previous bits.
2018 fl = self.d16_norm_f16(lo, is_norm) 2102 fl = self.d16_norm_f16(lo, is_norm, is_f32)
2019 self.emit(f"{r} = OpSelect %uint {is_int_fmt} {il} {fl}") 2103 self.emit(f"{r} = OpSelect %uint {is_int_fmt} {il} {fl}")
2020 self.write_lo16(dest, r) 2104 self.write_lo16(dest, r)
2021 continue 2105 continue
2022 hi = outs[i + 1] 2106 hi = outs[i + 1]
2023 ph = self.tmp() 2107 ph = self.tmp()
2024 fh_s = self.tmp() 2108 fh_s = self.tmp()
2025 self.emit(f"{fh_s} = OpShiftLeftLogical %uint {self.d16_norm_f16(hi, is_norm)} {self.cu(16)}") 2109 self.emit(f"{fh_s} = OpShiftLeftLogical %uint {self.d16_norm_f16(hi, is_norm, is_f32)} {self.cu(16)}")
2026 self.emit(f"{ph} = OpBitwiseOr %uint {self.d16_norm_f16(lo, is_norm)} {fh_s}") 2110 self.emit(f"{ph} = OpBitwiseOr %uint {self.d16_norm_f16(lo, is_norm, is_f32)} {fh_s}")
2027 ih, pi = self.tmp(), self.tmp() 2111 ih, pi = self.tmp(), self.tmp()
2028 high_half = int_half(hi) 2112 high_half = int_half(hi)
2029 self.emit(f"{ih} = OpShiftLeftLogical %uint {high_half} {self.cu(16)}") 2113 self.emit(f"{ih} = OpShiftLeftLogical %uint {high_half} {self.cu(16)}")
@@ -2036,15 +2120,21 @@ class Gen:
2036 # quotient is below the halfway point each time, and RDNA2 rounds it once, straight to f16 (BUILD-161, RX 6700). 2120 # quotient is below the halfway point each time, and RDNA2 rounds it once, straight to f16 (BUILD-161, RX 6700).
2037 D16_NORM_HALFWAY = (0x3F7FF000, 0x3F7FB000) 2121 D16_NORM_HALFWAY = (0x3F7FF000, 0x3F7FB000)
2038 2122
2039 def d16_norm_f16(self, bits, is_norm): 2123 def d16_norm_f16(self, bits, is_norm, is_f32=None):
2040 """f16 bits of a typed d16 buffer load component from its decoded f32 ``bits``. Round to nearest even 2124 """f16 bits of a typed d16 buffer load component from its decoded f32 ``bits``. Round to nearest even
2041 (f16_bits), except that a UNORM/SNORM quotient (``is_norm``) whose f32 is one of D16_NORM_HALFWAY takes the 2125 (f16_bits), except that a UNORM/SNORM quotient (``is_norm``) whose f32 is one of D16_NORM_HALFWAY takes the
2042 f16 below it. The hardware rounds the exact quotient once; f32 first and then f16 rounds twice, which is 1 ulp 2126 f16 below it. The hardware rounds the exact quotient once; f32 first and then f16 rounds twice, which is 1 ulp
2043 high on exactly those values (UNORM16 0xffaf and 0xffef, SNORM16 0x7ff7 and 0x8009, the 14- and 15-bit 2127 high on exactly those values (UNORM16 0xffaf and 0xffef, SNORM16 0x7ff7 and 0x8009, the 14- and 15-bit
2044 twins). Measured on an RX 6700 (gfx1031) for every UNORM8/SNORM8/UNORM10/UNORM16/SNORM16 value, MUBUF and 2128 twins). Measured on an RX 6700 (gfx1031) for every UNORM8/SNORM8/UNORM10/UNORM16/SNORM16 value, MUBUF and
2045 MTBUF, wave32 and wave64 (tools/d16_format_probe.py). A float format keeps the plain rounding: a 32_FLOAT 2129 MTBUF, wave32 and wave64 (tools/d16_format_probe.py). A 32-bit float format (``is_f32``) is narrowed toward
2046 0x3f7ff000 is a real tie.""" 2130 zero instead, finite values past the range giving +-65504: measured natively on gfx1036 for 32_FLOAT,
2131 32_32_FLOAT and 32_32_32_32_FLOAT, d16_x/xy/xyzw, wave32 and wave64 (SHADER-358)."""
2047 h = self.f16_bits(self.tof(bits)) 2132 h = self.f16_bits(self.tof(bits))
2133 if is_f32 is not None:
2134 hz, sel = self.tmp(), self.tmp()
2135 self.emit(f"{hz} = OpCopyObject %uint {self.mem_f16(self.tof(bits))}")
2136 self.emit(f"{sel} = OpSelect %uint {is_f32} {hz} {h}")
2137 h = sel
2048 mag, a, b, hit, both, dn, out = (self.tmp() for _ in range(7)) 2138 mag, a, b, hit, both, dn, out = (self.tmp() for _ in range(7))
2049 self.emit(f"{mag} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}") 2139 self.emit(f"{mag} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}")
2050 self.emit(f"{a} = OpIEqual %bool {mag} {self.cu(self.D16_NORM_HALFWAY[0])}") 2140 self.emit(f"{a} = OpIEqual %bool {mag} {self.cu(self.D16_NORM_HALFWAY[0])}")
@@ -2255,8 +2345,9 @@ class Gen:
2255 2345
2256 def buf_dword_ptr(self, arr, host, step, i): 2346 def buf_dword_ptr(self, arr, host, step, i):
2257 """Pointer to dword i (a Python int or a uint id) of a buffer access whose first dword is at host address 2347 """Pointer to dword i (a Python int or a uint id) of a buffer access whose first dword is at host address
2258 `host`, `arr` the same address as a PSB array: arr[i] for the linear layout (step None), else host + i * step, 2348 `host`, `arr` the same address as a PSB array: arr[i] for the linear layout (step None), else host + i * step
2259 since dword k of a swizzled access is 4 * index_stride bytes after dword k - 1 (buffer_address).""" 2349 in scratch-swizzle mode (SWIZZLE_ENABLE=1, idxen=0, ADD_TID_ENABLE=1), where dword k is 4 * index_stride
2350 bytes after dword k - 1 (buffer_address)."""
2260 ix = self.cu(i) if isinstance(i, int) else i 2351 ix = self.cu(i) if isinstance(i, int) else i
2261 p = self.tmp() 2352 p = self.tmp()
2262 if step is None or i == 0: 2353 if step is None or i == 0:
@@ -2270,25 +2361,26 @@ class Gen:
2270 return p 2361 return p
2271 2362
2272 def buffer_address(self, a, mods, parts=False, elem=None, fixed_fmt=None): 2363 def buffer_address(self, a, mods, parts=False, elem=None, fixed_fmt=None):
2273 """(64-bit element address id, V# word3 id, in_bounds bool id) for a MUBUF/MTBUF instruction: vdata, vaddr, 2364 """(64-bit element address id, V# word3 id, in_bounds bool id, ..., step) for a MUBUF/MTBUF instruction:
2274 srsrc, soffset. The address is V#.base + soffset + inst_offset + (offen ? vaddr : 0) + (idxen ? vindex * 2365 vdata, vaddr, srsrc, soffset. With `idx` = idxen ? vindex : (ADD_TID_ENABLE ? lane : 0) (idxen ignores
2275 stride : 0), byte exact. in_bounds is the V# OOB_SELECT (word3 bits [29:28]) check of the first dword, shared 2366 ADD_TID_ENABLE), `off` = uint32((offen ? vaddr : 0) + inst_offset) (32-bit wrap), `offs` = uint64(off) +
2276 by stores, atomics and format loads. With `idx` = vindex (0 without idxen), `off` = inst_offset + vaddr offset 2367 uint64(soffset) (64-bit, no wrap), out of range on RDNA2 as measured natively on gfx1036
2277 (offen), `offs` = off + soffset, out of range on RDNA2 as measured natively on gfx1036 (docs/buffer_bounds.md, 2368 (docs/buffer_bounds.md, docs/design.md):
2278 Mesa's GFX11 column) when, for a dword at byte k * 4 of the access:
2279 0 STRUCTURED_WITH_OFFSET: idx >= num_records or off + 4k + 4 > stride 2369 0 STRUCTURED_WITH_OFFSET: idx >= num_records or off + 4k + 4 > stride
2280 1 STRUCTURED: idx >= num_records 2370 1 STRUCTURED: idx >= num_records
2281 2 DISABLED: num_records == 0 2371 2 DISABLED: num_records == 0
2282 3 RAW: offs + 4k + 4 > num_records (idx * stride is not part of the check) 2372 3 RAW (linear or stride 0): offs + 4k + 4 > num_records
2283 A V# word3 that an s_mov_b32 wrote earlier in the block (`sgpr_imm`) folds to one of these; a run-time one 2373 3 SWIZZLED (swz_active and stride != 0): uint64(idx) + uint64(soffset) >= num_records or off + 4k + 4 > stride
2284 selects with OpSelect. elem="fmt" is for typed loads and stores: the whole element (its format's size, from the 2374 SWIZZLE_ENABLE (word1[31]) activates only when idxen or ADD_TID_ENABLE is active (`swz_active`); with neither,
2285 instruction's fixed_fmt, a literal word3 or the V# at run time) must end inside. parts=True adds a 4th element for buffer_load: a function k -> in-range bool id for 2375 addressing is linear and mode 3 stays RAW. Two swizzle sub-modes exist on RDNA2 (measured natively on gfx1036,
2286 dword k (modes 0 and 3, and a run-time V#), or None when the literal mode is 1 or 2 (every dword shares 2376 wave32 & wave64):
2287 in_bounds). Multi-dword loads are per dword for mode 3 (measured, RX 6800); mode 0 is by analogy. 2377 - Scratch swizzle (`SWIZZLE_ENABLE=1, idxen=0, ADD_TID_ENABLE=1`): raw multi-dword accesses step by
2288 A swizzled V# (SWIZZLE_ENABLE) gets the RDNA2 ISA's swizzled buffer_offset, ADD_TID_ENABLE adds the wave lane 2378 `4 * index_stride` bytes (`step`), and typed formats > 4 bytes (plus 8-byte `buffer_atomic_*_x2`) are
2289 to idx, and mode 3 checks like mode 0 when swizzled with a stride (ISA table 35). Every tuple ends with `step`: 2379 suppressed (even in mode 2).
2290 None when consecutive dwords of the access are 4 bytes apart, else the id of that distance (4 * index_stride 2380 - Indexed swizzle (`SWIZZLE_ENABLE=1, idxen=1`): multi-dword raw, typed, and `_x2` atomic accesses step
2291 when swizzled, selected at run time for a run-time word1), for buf_dword_ptr.""" 2381 linearly by `+4` bytes (`step = None`), and typed formats > 4 bytes execute normally.
2382 A literal V# word1/word3 (`sgpr_imm`) folds each bit; a run-time one selects dynamically. elem="fmt" checks the
2383 whole element's format size; parts=True adds a 4th element `k -> in-range bool id` for per-dword checks."""
2292 vaddr, rsrc = a[1], a[2] 2384 vaddr, rsrc = a[1], a[2]
2293 soff = a[3] if len(a) > 3 else {"k": "imm", "v": 0} 2385 soff = a[3] if len(a) > 3 else {"k": "imm", "v": 0}
2294 if (rsrc["k"] == "sgpr" and rsrc.get("n") == 4): 2386 if (rsrc["k"] == "sgpr" and rsrc.get("n") == 4):
@@ -2302,57 +2394,88 @@ class Gen:
2302 hi, stride = self.tmp(), self.tmp() 2394 hi, stride = self.tmp(), self.tmp()
2303 self.emit(f"{hi} = OpBitwiseAnd %uint {d1} {self.cu(0xFFFF)}") 2395 self.emit(f"{hi} = OpBitwiseAnd %uint {d1} {self.cu(0xFFFF)}")
2304 self.emit(f"{stride} = OpBitFieldUExtract %uint {d1} {self.cu(16)} {self.cu(14)}") 2396 self.emit(f"{stride} = OpBitFieldUExtract %uint {d1} {self.cu(16)} {self.cu(14)}")
2305 # Swizzled buffers (docs/design.md, Swizzled buffer addressing; RDNA2 ISA 8.1.5 "Swizzled Buffer Addressing" 2397 # Swizzled buffers (docs/design.md, Swizzled buffer addressing; native gfx1036 measurement): SWIZZLE_ENABLE is
2306 # and table 35; fields from Mesa gfx10-rsrc.json SQ_BUF_RSRC_WORD1/WORD3): SWIZZLE_ENABLE is word1 bit 31, 2398 # word1[31], INDEX_STRIDE word3[22:21] (IS = 8 << n), ADD_TID_ENABLE word3[23], element_size fixed at 4.
2307 # INDEX_STRIDE word3 [22:21] (IS = 8 << n indices), ADD_TID_ENABLE word3 bit 23, element_size fixed at 4. 2399 # A literal word folds its bit (a Python bool); a run-time one is None.
2308 # A literal word folds its bit (a Python bool); a run-time one is a SPIR-V id (0 or 1).
2309 swz = bool(lit1 >> 31) if lit1 is not None else None 2400 swz = bool(lit1 >> 31) if lit1 is not None else None
2310 tid = bool(lit3 >> 23 & 1) if lit3 is not None else None 2401 tid = bool(lit3 >> 23 & 1) if lit3 is not None else None
2402 has_idx = "idxen" in mods
2311 inst = next((int(m.split(":")[1], 0) for m in mods if m.startswith("offset:")), 0) 2403 inst = next((int(m.split(":")[1], 0) for m in mods if m.startswith("offset:")), 0)
2404 soff_zero = soff["k"] == "imm" and soff["v"] == 0
2312 soff_v = self.src_u(soff) 2405 soff_v = self.src_u(soff)
2313 total = self.tmp()
2314 self.emit(f"{total} = OpIAdd %uint {soff_v} {self.cu(inst)}")
2315 vregs = [] if vaddr["k"] == "special" else [vaddr["r"] + i for i in range(vaddr.get("n", 1))] 2406 vregs = [] if vaddr["k"] == "special" else [vaddr["r"] + i for i in range(vaddr.get("n", 1))]
2316 idx = None
2317 if "idxen" in mods:
2318 idx = self.load_reg("vgpr", vregs[0])
2319 voff = None 2407 voff = None
2320 if "offen" in mods: 2408 if "offen" in mods:
2321 voff = self.load_reg("vgpr", vregs[1] if "idxen" in mods else vregs[0]) 2409 voff = self.load_reg("vgpr", vregs[1] if has_idx else vregs[0])
2322 # ADD_TID_ENABLE adds the lane within the wave (thread_id[5:0]) to the index, swizzled or linear (ISA table 2410 # Effective index: idxen uses vindex alone and ignores ADD_TID_ENABLE; without idxen, ADD_TID_ENABLE supplies
2323 # 33 and the Ring/stream-out column of table 36, which is linear with add_tid); the bounds check sees it too 2411 # the wave lane (thread_id[5:0]).
2324 if tid is not False: 2412 tid_b = None
2413 if has_idx:
2414 idx = self.load_reg("vgpr", vregs[0])
2415 elif tid is False:
2416 idx = None
2417 else:
2325 lane = self.wave_lane() 2418 lane = self.wave_lane()
2326 if tid is None: # lane * the run-time bit 2419 if tid is None: # lane * run-time ADD_TID_ENABLE
2327 b, t = self.tmp(), self.tmp() 2420 tid_b, idx = self.tmp(), self.tmp()
2328 self.emit(f"{b} = OpBitFieldUExtract %uint {d3} {self.cu(23)} {self.cu(1)}") 2421 self.emit(f"{tid_b} = OpBitFieldUExtract %uint {d3} {self.cu(23)} {self.cu(1)}")
2329 self.emit(f"{t} = OpIMul %uint {lane} {b}") 2422 self.emit(f"{idx} = OpIMul %uint {lane} {tid_b}")
2330 lane = t 2423 else:
2331 if idx is None:
2332 idx = lane 2424 idx = lane
2425 # SWIZZLE_ENABLE activates only with idxen or ADD_TID_ENABLE; scratch-swizzle stepping/suppression applies only
2426 # when SWIZZLE_ENABLE=1, idxen=0, ADD_TID_ENABLE=1.
2427 swz_u = None
2428 if has_idx:
2429 swz_active = swz
2430 scratch_swz = False
2431 if swz_active is None:
2432 swz_u = self.tmp()
2433 self.emit(f"{swz_u} = OpBitFieldUExtract %uint {d1} {self.cu(31)} {self.cu(1)}")
2434 elif swz is False or tid is False:
2435 swz_active = False
2436 scratch_swz = False
2437 elif swz is True and tid is True:
2438 swz_active = True
2439 scratch_swz = True
2440 else:
2441 swz_active = None
2442 scratch_swz = None
2443 if swz is True:
2444 swz_u = tid_b
2333 else: 2445 else:
2334 s = self.tmp() 2446 swz_b = self.tmp()
2335 self.emit(f"{s} = OpIAdd %uint {idx} {lane}") 2447 self.emit(f"{swz_b} = OpBitFieldUExtract %uint {d1} {self.cu(31)} {self.cu(1)}")
2336 idx = s 2448 if tid is True:
2337 # offs = soffset + inst_offset + vaddr offset (idx * stride excluded): the raw bounds check's offset 2449 swz_u = swz_b
2338 offs = total 2450 else:
2451 swz_u = self.tmp()
2452 self.emit(f"{swz_u} = OpBitwiseAnd %uint {swz_b} {tid_b}")
2453 # off = uint32((offen ? voff : 0) + inst_offset): wraps at 32 bits on RDNA2.
2339 if voff is not None: 2454 if voff is not None:
2340 offs = self.tmp() 2455 if inst:
2341 self.emit(f"{offs} = OpIAdd %uint {total} {voff}") 2456 off = self.tmp()
2342 total = offs 2457 self.emit(f"{off} = OpIAdd %uint {voff} {self.cu(inst)}")
2343 # step: bytes between consecutive dwords of one access, None for the linear 4 (callers index an array then) 2458 else:
2459 off = voff
2460 else:
2461 off = self.cu(inst)
2462 # step: bytes between consecutive dwords of a raw access, None for linear +4 (including all idxen=1 and fmt).
2344 step = None 2463 step = None
2345 if swz is False: 2464 if swz_active is False:
2465 if soff_zero:
2466 total = off
2467 else:
2468 total = self.tmp()
2469 self.emit(f"{total} = OpIAdd %uint {soff_v} {off}")
2346 if idx is not None: 2470 if idx is not None:
2347 m, total = self.tmp(), self.tmp() 2471 m, t = self.tmp(), self.tmp()
2348 self.emit(f"{m} = OpIMul %uint {idx} {stride}") 2472 self.emit(f"{m} = OpIMul %uint {idx} {stride}")
2349 self.emit(f"{total} = OpIAdd %uint {offs} {m}") 2473 self.emit(f"{t} = OpIAdd %uint {total} {m}")
2474 total = t
2350 sw3 = False 2475 sw3 = False
2351 else: 2476 else:
2352 # buffer_offset = (index / IS * stride + offset / 4 * 4) * IS + index % IS * 4 + offset % 4, Offset = 2477 # buffer_offset = (index / IS * stride + (off & ~3)) * IS + (index % IS) * 4 + (off & 3), IS = 2^L;
2353 # inst_offset + vaddr offset (no soffset), added to base + soffset; IS = 2^L. Dword k of the access is 2478 # L = 0 (run-time V# with swz_u == 0) reduces to the linear address index * stride + off.
2354 # element offset / 4 + k, 4 * IS bytes further. L = 0 (a run-time V# without SWIZZLE_ENABLE) is the
2355 # linear address: index * stride + offset. 32-bit arithmetic, like the linear address.
2356 if lit3 is not None: 2479 if lit3 is not None:
2357 Li = 3 + (lit3 >> 21 & 3) 2480 Li = 3 + (lit3 >> 21 & 3)
2358 L = self.cu(Li) 2481 L = self.cu(Li)
@@ -2360,48 +2483,49 @@ class Gen:
2360 f, L, Li = self.tmp(), self.tmp(), None 2483 f, L, Li = self.tmp(), self.tmp(), None
2361 self.emit(f"{f} = OpBitFieldUExtract %uint {d3} {self.cu(21)} {self.cu(2)}") 2484 self.emit(f"{f} = OpBitFieldUExtract %uint {d3} {self.cu(21)} {self.cu(2)}")
2362 self.emit(f"{L} = OpIAdd %uint {f} {self.cu(3)}") 2485 self.emit(f"{L} = OpIAdd %uint {f} {self.cu(3)}")
2363 if swz is None: # L * the run-time bit: 0 when not swizzled 2486 if swz_active is None: # L * swz_u: 0 when not swizzled
2364 b, t = self.tmp(), self.tmp() 2487 t = self.tmp()
2365 self.emit(f"{b} = OpBitFieldUExtract %uint {d1} {self.cu(31)} {self.cu(1)}") 2488 self.emit(f"{t} = OpIMul %uint {L} {swz_u}")
2366 self.emit(f"{t} = OpIMul %uint {L} {b}")
2367 L, Li = t, None 2489 L, Li = t, None
2368 off_s = self.cu(inst)
2369 if voff is not None:
2370 off_s = self.tmp()
2371 self.emit(f"{off_s} = OpIAdd %uint {voff} {self.cu(inst)}")
2372 om4, ol, sh = self.tmp(), self.tmp(), self.tmp() 2490 om4, ol, sh = self.tmp(), self.tmp(), self.tmp()
2373 self.emit(f"{om4} = OpBitwiseAnd %uint {off_s} {self.cu(0xFFFFFFFC)}") 2491 self.emit(f"{om4} = OpBitwiseAnd %uint {off} {self.cu(0xFFFFFFFC)}")
2374 self.emit(f"{ol} = OpBitwiseAnd %uint {off_s} {self.cu(3)}") 2492 self.emit(f"{ol} = OpBitwiseAnd %uint {off} {self.cu(3)}")
2375 if idx is not None: 2493 msb, ms, inner, lsb, l4, im = (self.tmp() for _ in range(6))
2376 msb, ms, inner, lsb, l4, im = (self.tmp() for _ in range(6)) 2494 self.emit(f"{msb} = OpShiftRightLogical %uint {idx} {L}")
2377 self.emit(f"{msb} = OpShiftRightLogical %uint {idx} {L}") 2495 self.emit(f"{ms} = OpIMul %uint {msb} {stride}")
2378 self.emit(f"{ms} = OpIMul %uint {msb} {stride}") 2496 self.emit(f"{inner} = OpIAdd %uint {ms} {om4}")
2379 self.emit(f"{inner} = OpIAdd %uint {ms} {om4}") 2497 self.emit(f"{sh} = OpShiftLeftLogical %uint {inner} {L}")
2380 self.emit(f"{sh} = OpShiftLeftLogical %uint {inner} {L}")
2381 if Li is not None:
2382 self.emit(f"{lsb} = OpBitwiseAnd %uint {idx} {self.cu((1 << Li) - 1)}")
2383 else: # index - (index >> L << L)
2384 hi_part = self.tmp()
2385 self.emit(f"{hi_part} = OpShiftLeftLogical %uint {msb} {L}")
2386 self.emit(f"{lsb} = OpISub %uint {idx} {hi_part}")
2387 self.emit(f"{l4} = OpShiftLeftLogical %uint {lsb} {self.cu(2)}")
2388 self.emit(f"{im} = OpIAdd %uint {sh} {l4}")
2389 sh = im
2390 else:
2391 self.emit(f"{sh} = OpShiftLeftLogical %uint {om4} {L}")
2392 b_off, total = self.tmp(), self.tmp()
2393 self.emit(f"{b_off} = OpIAdd %uint {sh} {ol}")
2394 self.emit(f"{total} = OpIAdd %uint {soff_v} {b_off}")
2395 if Li is not None: 2498 if Li is not None:
2396 step = self.cu(4 << Li) 2499 self.emit(f"{lsb} = OpBitwiseAnd %uint {idx} {self.cu((1 << Li) - 1)}")
2500 else: # index - (index >> L << L)
2501 hi_part = self.tmp()
2502 self.emit(f"{hi_part} = OpShiftLeftLogical %uint {msb} {L}")
2503 self.emit(f"{lsb} = OpISub %uint {idx} {hi_part}")
2504 self.emit(f"{l4} = OpShiftLeftLogical %uint {lsb} {self.cu(2)}")
2505 self.emit(f"{im} = OpIAdd %uint {sh} {l4}")
2506 b_off = self.tmp()
2507 self.emit(f"{b_off} = OpIAdd %uint {im} {ol}")
2508 if soff_zero:
2509 total = b_off
2397 else: 2510 else:
2398 step = self.tmp() 2511 total = self.tmp()
2399 self.emit(f"{step} = OpShiftLeftLogical %uint {self.cu(4)} {L}") 2512 self.emit(f"{total} = OpIAdd %uint {soff_v} {b_off}")
2400 # OOB_SELECT 3 with SWIZZLE_ENABLE and a stride != 0 checks like mode 0 (ISA table 35): index >= 2513 if elem != "fmt" and scratch_swz is not False:
2401 # num_records or offset + payload > stride, offset without soffset 2514 if Li is not None:
2402 if lit1 is not None: 2515 step = self.cu(4 << Li)
2403 sw3 = (lit1 >> 16 & 0x3FFF) != 0 2516 else:
2404 else: # L * stride != 0: swizzled (L >= 3) and a stride (no overflow) 2517 step = self.tmp()
2518 self.emit(f"{step} = OpShiftLeftLogical %uint {self.cu(4)} {L}")
2519 # OOB_SELECT 3 with active swizzle and stride != 0 checks (idx + soffset) >= num_records or off + payload > stride.
2520 if lit1 is not None and (lit1 >> 16 & 0x3FFF) == 0:
2521 sw3 = False
2522 elif swz_active is True:
2523 if lit1 is not None:
2524 sw3 = True
2525 else:
2526 sw3 = self.tmp()
2527 self.emit(f"{sw3} = OpINotEqual %bool {stride} {self.cu(0)}")
2528 else: # L * stride != 0: swz_u == 1 (L >= 3) and stride != 0 (no overflow)
2405 ls, sw3 = self.tmp(), self.tmp() 2529 ls, sw3 = self.tmp(), self.tmp()
2406 self.emit(f"{ls} = OpIMul %uint {L} {stride}") 2530 self.emit(f"{ls} = OpIMul %uint {L} {stride}")
2407 self.emit(f"{sw3} = OpINotEqual %bool {ls} {self.cu(0)}") 2531 self.emit(f"{sw3} = OpINotEqual %bool {ls} {self.cu(0)}")
@@ -2415,9 +2539,11 @@ class Gen:
2415 self.emit(f"{addr} = OpIAdd %ulong {base} {o64}") 2539 self.emit(f"{addr} = OpIAdd %ulong {base} {o64}")
2416 mode = None if lit3 is None else lit3 >> 28 & 3 2540 mode = None if lit3 is None else lit3 >> 28 & 3
2417 mode0_rule = mode in (None, 0) or (mode == 3 and sw3 is not False) 2541 mode0_rule = mode in (None, 0) or (mode == 3 and sw3 is not False)
2418 # idx (0 without idxen) < num_records and num_records != 0 do not depend on the dword; the two end checks do 2542 need_raw = mode in (None, 3) and sw3 is not True
2419 p1 = p2 = None 2543 need_p3 = mode in (None, 3) and sw3 is not False
2420 if mode in (None, 0, 1) or mode0_rule: 2544 need_p1 = mode in (None, 0, 1) or (need_p3 and soff_zero)
2545 p1 = p2 = p3_idx = None
2546 if need_p1:
2421 p1 = self.tmp() 2547 p1 = self.tmp()
2422 if idx is None: 2548 if idx is None:
2423 self.emit(f"{p1} = OpINotEqual %bool {d2} {self.cu(0)}") 2549 self.emit(f"{p1} = OpINotEqual %bool {d2} {self.cu(0)}")
@@ -2426,20 +2552,39 @@ class Gen:
2426 if mode in (None, 2): 2552 if mode in (None, 2):
2427 p2 = self.tmp() 2553 p2 = self.tmp()
2428 self.emit(f"{p2} = OpINotEqual %bool {d2} {self.cu(0)}") 2554 self.emit(f"{p2} = OpINotEqual %bool {d2} {self.cu(0)}")
2555 off64 = d2_64 = soff64 = None
2556 if mode0_rule or need_raw:
2557 off64 = self.tmp()
2558 self.emit(f"{off64} = OpUConvert %ulong {off}")
2559 if need_raw or (need_p3 and not soff_zero and idx is not None):
2560 d2_64 = self.tmp()
2561 self.emit(f"{d2_64} = OpUConvert %ulong {d2}")
2562 if not soff_zero and (need_raw or (need_p3 and idx is not None)):
2563 soff64 = self.tmp()
2564 self.emit(f"{soff64} = OpUConvert %ulong {soff_v}")
2565 if need_p3:
2566 if soff_zero:
2567 p3_idx = p1
2568 elif idx is None:
2569 p3_idx = self.tmp()
2570 self.emit(f"{p3_idx} = OpULessThan %bool {soff_v} {d2}")
2571 else:
2572 idx64, idx_s, p3_idx = self.tmp(), self.tmp(), self.tmp()
2573 self.emit(f"{idx64} = OpUConvert %ulong {idx}")
2574 self.emit(f"{idx_s} = OpIAdd %ulong {idx64} {soff64}")
2575 self.emit(f"{p3_idx} = OpULessThan %bool {idx_s} {d2_64}")
2429 lim = {} 2576 lim = {}
2430 if mode0_rule: 2577 if mode0_rule:
2431 # off = inst_offset + vaddr offset, without soffset (docs/buffer_bounds.md) 2578 st64 = self.tmp()
2432 off = self.cu(inst) 2579 self.emit(f"{st64} = OpUConvert %ulong {stride}")
2433 if voff is not None: 2580 lim[0] = (off64, st64)
2434 off = self.tmp() 2581 if need_raw:
2435 self.emit(f"{off} = OpIAdd %uint {voff} {self.cu(inst)}") 2582 if soff_zero:
2436 lim[0] = (self.tmp(), self.tmp()) 2583 offs64 = off64
2437 self.emit(f"{lim[0][0]} = OpUConvert %ulong {off}") 2584 else:
2438 self.emit(f"{lim[0][1]} = OpUConvert %ulong {stride}") 2585 offs64 = self.tmp()
2439 if mode in (None, 3): 2586 self.emit(f"{offs64} = OpIAdd %ulong {off64} {soff64}")
2440 lim[3] = (self.tmp(), self.tmp()) 2587 lim[3] = (offs64, d2_64)
2441 self.emit(f"{lim[3][0]} = OpUConvert %ulong {offs}")
2442 self.emit(f"{lim[3][1]} = OpUConvert %ulong {d2}")
2443 sel = None 2588 sel = None
2444 if mode is None: 2589 if mode is None:
2445 md, m1, m2, m3 = (self.tmp() for _ in range(4)) 2590 md, m1, m2, m3 = (self.tmp() for _ in range(4))
@@ -2458,15 +2603,15 @@ class Gen:
2458 self.emit(f"{ok} = OpULessThanEqual %bool {end} {limit}") 2603 self.emit(f"{ok} = OpULessThanEqual %bool {end} {limit}")
2459 return ok 2604 return ok
2460 2605
2461 def raw_or_swizzled(e0, end_bytes): 2606 def raw_or_swizzled(e3_sw, end_bytes):
2462 """mode 3: the raw end check, or mode 0's e0 for a swizzled V# with a stride (sw3).""" 2607 """mode 3: the raw end check, or the swizzled-with-stride check (sw3)."""
2463 if sw3 is True: 2608 if sw3 is True:
2464 return e0 2609 return e3_sw
2465 raw = end_ok(3, end_bytes) 2610 raw = end_ok(3, end_bytes)
2466 if sw3 is False: 2611 if sw3 is False:
2467 return raw 2612 return raw
2468 r = self.tmp() 2613 r = self.tmp()
2469 self.emit(f"{r} = OpSelect %bool {sw3} {e0} {raw}") 2614 self.emit(f"{r} = OpSelect %bool {sw3} {e3_sw} {raw}")
2470 return r 2615 return r
2471 2616
2472 def check_end(end_bytes): 2617 def check_end(end_bytes):
@@ -2477,16 +2622,30 @@ class Gen:
2477 return p2 2622 return p2
2478 if mode == 3 and sw3 is False: 2623 if mode == 3 and sw3 is False:
2479 return end_ok(3, end_bytes) 2624 return end_ok(3, end_bytes)
2480 e0 = self.tmp() 2625 off_ok = end_ok(0, end_bytes)
2481 self.emit(f"{e0} = OpLogicalAnd %bool {p1} {end_ok(0, end_bytes)}")
2482 if mode == 0: 2626 if mode == 0:
2627 e0 = self.tmp()
2628 self.emit(f"{e0} = OpLogicalAnd %bool {p1} {off_ok}")
2483 return e0 2629 return e0
2484 if mode == 3: 2630 if mode == 3:
2485 return raw_or_swizzled(e0, end_bytes) 2631 e3_sw = self.tmp()
2632 self.emit(f"{e3_sw} = OpLogicalAnd %bool {p3_idx} {off_ok}")
2633 return raw_or_swizzled(e3_sw, end_bytes)
2634 e0 = self.tmp()
2635 self.emit(f"{e0} = OpLogicalAnd %bool {p1} {off_ok}")
2636 if sw3 is False:
2637 e3 = end_ok(3, end_bytes)
2638 else:
2639 if p3_idx == p1:
2640 e3_sw = e0
2641 else:
2642 e3_sw = self.tmp()
2643 self.emit(f"{e3_sw} = OpLogicalAnd %bool {p3_idx} {off_ok}")
2644 e3 = raw_or_swizzled(e3_sw, end_bytes)
2486 s12, s3, r = self.tmp(), self.tmp(), self.tmp() 2645 s12, s3, r = self.tmp(), self.tmp(), self.tmp()
2487 self.emit(f"{s12} = OpSelect %bool {sel[0]} {p1} {e0}") 2646 self.emit(f"{s12} = OpSelect %bool {sel[0]} {p1} {e0}")
2488 self.emit(f"{s3} = OpSelect %bool {sel[1]} {p2} {s12}") 2647 self.emit(f"{s3} = OpSelect %bool {sel[1]} {p2} {s12}")
2489 self.emit(f"{r} = OpSelect %bool {sel[2]} {raw_or_swizzled(e0, end_bytes)} {s3}") 2648 self.emit(f"{r} = OpSelect %bool {sel[2]} {e3} {s3}")
2490 return r 2649 return r
2491 2650
2492 def check(k): 2651 def check(k):
@@ -2514,7 +2673,33 @@ class Gen:
2514 size = self.tmp() 2673 size = self.tmp()
2515 self.emit(f"{size} = OpUConvert %ulong {sz}") 2674 self.emit(f"{size} = OpUConvert %ulong {sz}")
2516 in_b = check_end(size) 2675 in_b = check_end(size)
2517 return addr, d3, in_b, step 2676 if scratch_swz is not False:
2677 # Native gfx1036 measurement (wave32 & wave64): in scratch-swizzle mode (SWIZZLE_ENABLE=1, idxen=0,
2678 # ADD_TID_ENABLE=1), typed formats > 4 bytes and 8-byte buffer_atomic_*_x2 are suppressed even in
2679 # OOB_SELECT 2 (DISABLED).
2680 if isinstance(size, int):
2681 if size > 4:
2682 if scratch_swz is True:
2683 in_b = "%false"
2684 else:
2685 ns, ok = self.tmp(), self.tmp()
2686 self.emit(f"{ns} = OpIEqual %bool {swz_u} {self.cu(0)}")
2687 self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {ns}")
2688 in_b = ok
2689 else:
2690 le4 = self.tmp()
2691 self.emit(f"{le4} = OpULessThanEqual %bool {size} {self.cl(4)}")
2692 if scratch_swz is True:
2693 ok = self.tmp()
2694 self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {le4}")
2695 in_b = ok
2696 else:
2697 ns, allow, ok = self.tmp(), self.tmp(), self.tmp()
2698 self.emit(f"{ns} = OpIEqual %bool {swz_u} {self.cu(0)}")
2699 self.emit(f"{allow} = OpLogicalOr %bool {ns} {le4}")
2700 self.emit(f"{ok} = OpLogicalAnd %bool {in_b} {allow}")
2701 in_b = ok
2702 return addr, d3, in_b, None
2518 in_b = check(0) 2703 in_b = check(0)
2519 if parts: 2704 if parts:
2520 # modes 0 and 3 end-check every dword on its own; 1 and 2 (a literal V#) share the first-byte check 2705 # modes 0 and 3 end-check every dword on its own; 1 and 2 (a literal V#) share the first-byte check
@@ -2645,6 +2830,36 @@ class Gen:
2645 extended = self.tmp() 2830 extended = self.tmp()
2646 self.emit(f"{extended} = OpBitFieldSExtract %int {self.as_int(component)} {self.cu(0)} {self.cu(16)}") 2831 self.emit(f"{extended} = OpBitFieldSExtract %int {self.as_int(component)} {self.cu(0)} {self.cu(16)}")
2647 signed_ic.append(self.tou(extended)) 2832 signed_ic.append(self.tou(extended))
2833 signed_ic = signed_ic + [self.cu(0)] * (4 - len(signed_ic))
2834 # MUBUF 2-component stores infer COMP_SWAP from V# DST_SEL_X/Y/Z (measured natively on gfx1036 across
2835 # all 1,296 valid DST_SEL tuples, wave32 and wave64): XY01 -> (x, y), YX01 -> (y, x), XYZW -> (x, w),
2836 # YXZW/ZYXW -> (w, x). MTBUF (fixed_fmt is not None) ignores DST_SEL and always stores (x, y).
2837 if fixed_fmt is None:
2838 sx, sy, sz = self.tmp(), self.tmp(), self.tmp()
2839 self.emit(f"{sx} = OpBitFieldUExtract %uint {d3} {self.cu(0)} {self.cu(3)}")
2840 self.emit(f"{sy} = OpBitFieldUExtract %uint {d3} {self.cu(3)} {self.cu(3)}")
2841 self.emit(f"{sz} = OpBitFieldUExtract %uint {d3} {self.cu(6)} {self.cu(3)}")
2842 sy_reg, sz_reg, sz_const, use_y = (self.tmp() for _ in range(4))
2843 self.emit(f"{sy_reg} = OpUGreaterThanEqual %bool {sy} {self.cu(4)}")
2844 self.emit(f"{sz_reg} = OpUGreaterThanEqual %bool {sz} {self.cu(4)}")
2845 self.emit(f"{sz_const} = OpLogicalNot %bool {sz_reg}")
2846 self.emit(f"{use_y} = OpLogicalAnd %bool {sy_reg} {sz_const}")
2847 sx_ne4, yz_reg, rev2 = self.tmp(), self.tmp(), self.tmp()
2848 self.emit(f"{sx_ne4} = OpINotEqual %bool {sx} {self.cu(4)}")
2849 self.emit(f"{yz_reg} = OpLogicalOr %bool {sy_reg} {sz_reg}")
2850 self.emit(f"{rev2} = OpLogicalAnd %bool {sx_ne4} {yz_reg}")
2851
2852 def swiz2(arr):
2853 sec, c0, c1 = self.tmp(), self.tmp(), self.tmp()
2854 self.emit(f"{sec} = OpSelect %uint {use_y} {arr[1]} {arr[3]}")
2855 self.emit(f"{c0} = OpSelect %uint {rev2} {sec} {arr[0]}")
2856 self.emit(f"{c1} = OpSelect %uint {rev2} {arr[0]} {sec}")
2857 return [c0, c1]
2858
2859 norm2 = swiz2(unorm_rgba)
2860 fc2 = swiz2(fc)
2861 ic2 = swiz2(ic)
2862 signed_ic2 = swiz2(signed_ic) if d16 else ic2
2648 formats = self.FORMATS.items() if fmt is not None else [(fixed_fmt, self.FORMATS[fixed_fmt])] 2863 formats = self.FORMATS.items() if fmt is not None else [(fixed_fmt, self.FORMATS[fixed_fmt])]
2649 for code, (size, kind, widths) in formats: 2864 for code, (size, kind, widths) in formats:
2650 if fmt is not None: 2865 if fmt is not None:
@@ -2655,12 +2870,16 @@ class Gen:
2655 self.emit(f"OpBranchConditional {e} {ld} {le}") 2870 self.emit(f"OpBranchConditional {e} {ld} {le}")
2656 self.emit(f"{ld} = OpLabel") 2871 self.emit(f"{ld} = OpLabel")
2657 ncomp = min(len(widths), n) 2872 ncomp = min(len(widths), n)
2658 source = normalized if kind in ("unorm", "snorm") else fc 2873 if len(widths) == 2 and fixed_fmt is None:
2659 fcs = source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) 2874 fcs = norm2 if kind in ("unorm", "snorm") else fc2
2660 if code in (50, 56): 2875 ics = signed_ic2 if kind in ("i32", "sint") else ic2
2661 fcs = unorm_view 2876 else:
2662 integer_source = signed_ic if kind in ("i32", "sint") else ic 2877 source = normalized if kind in ("unorm", "snorm") else fc
2663 ics = integer_source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp) 2878 fcs = source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp)
2879 if code in (50, 56):
2880 fcs = unorm_view
2881 integer_source = signed_ic if kind in ("i32", "sint") else ic
2882 ics = integer_source[:ncomp] + [self.cu(0)] * (len(widths) - ncomp)
2664 words = self.encode_format(fcs + [self.cu(0)] * 4, ics + [self.cu(0)] * 4, code) 2883 words = self.encode_format(fcs + [self.cu(0)] * 4, ics + [self.cu(0)] * 4, code)
2665 if size >= 4: 2884 if size >= 4:
2666 for k, w in enumerate(words[:size // 4]): 2885 for k, w in enumerate(words[:size // 4]):
@@ -3376,7 +3595,7 @@ class Gen:
3376 def park_masks(self, blocks): 3595 def park_masks(self, blocks):
3377 """Run the lane-mask analysis and give every VGPR lane a mask is fetched back from a slot of its own, 3596 """Run the lane-mask analysis and give every VGPR lane a mask is fetched back from a slot of its own,
3378 after the real registers in the %sgpr array (the array grows by as many).""" 3597 after the real registers in the %sgpr array (the array grows by as many)."""
3379 self.lane_masks, self.mask_writes = lane_masks.analyse(*blocks) 3598 self.lane_masks, self.mask_writes, self.lane_either = lane_masks.analyse(*blocks, include_either=True)
3380 # lane_masks merges a mask on one path with plain data on another by dropping the register, 3599 # lane_masks merges a mask on one path with plain data on another by dropping the register,
3381 # so "not in cur_masks" does not prove it is data on every path. Keep a conservative set. 3600 # so "not in cur_masks" does not prove it is data on every path. Keep a conservative set.
3382 self.ever_mask = {r for m in self.lane_masks.values() for r in m if isinstance(r, int)} 3601 self.ever_mask = {r for m in self.lane_masks.values() for r in m if isinstance(r, int)}
@@ -3427,7 +3646,13 @@ class Gen:
3427 t = a.get("t", "") 3646 t = a.get("t", "")
3428 return t.startswith("exec") or (t in ("vcc", "vcc_lo") and "vcc" in self.cur_masks) or \ 3647 return t.startswith("exec") or (t in ("vcc", "vcc_lo") and "vcc" in self.cur_masks) or \
3429 (t == "vcc_hi" and self.wave64 and "vcc" in self.cur_masks) 3648 (t == "vcc_hi" and self.wave64 and "vcc" in self.cur_masks)
3430 return a["k"] == "sgpr" and all(a["r"] + i in self.cur_masks for i in range(a.get("n", 1))) 3649 if a["k"] == "sgpr":
3650 n = a.get("n", 1)
3651 if n == 2:
3652 return any(a["r"] + i in self.cur_masks for i in range(2)) and \
3653 all(a["r"] + i in self.cur_masks or a["r"] + i in self.cur_either for i in range(2))
3654 return all(a["r"] + i in self.cur_masks for i in range(n))
3655 return False
3431 3656
3432 def any_mask_word(self, a): 3657 def any_mask_word(self, a):
3433 """Whether any dword of an SGPR pair is a lane mask (EITHER constants are data here). 3658 """Whether any dword of an SGPR pair is a lane mask (EITHER constants are data here).
@@ -3456,7 +3681,8 @@ class Gen:
3456 if special: 3681 if special:
3457 key = ("exec", self.x_gen, self.x_tok.get("%active", "start")) 3682 key = ("exec", self.x_gen, self.x_tok.get("%active", "start"))
3458 elif a["k"] == "sgpr": 3683 elif a["k"] == "sgpr":
3459 key = ("v", self.x_gen, self.x_tok.get(("sgpr", a["r"]), ("start", a["r"]))) 3684 toks = tuple(self.x_tok.get(("sgpr", a["r"] + i), ("start", a["r"] + i)) for i in range(a.get("n", 1)))
3685 key = ("v", self.x_gen, toks)
3460 elif a["k"] == "special" and a["t"] in ("vcc", "vcc_lo", "vcc_hi"): 3686 elif a["k"] == "special" and a["t"] in ("vcc", "vcc_lo", "vcc_hi"):
3461 key = ("v", self.x_gen, self.x_tok.get("%vcc", ("start", "vcc"))) 3687 key = ("v", self.x_gen, self.x_tok.get("%vcc", ("start", "vcc")))
3462 if key in self.x_mcache: 3688 if key in self.x_mcache:
@@ -3641,6 +3867,12 @@ class Gen:
3641 lane, 5 every lane).""" 3867 lane, 5 every lane)."""
3642 if a["k"] == "sgpr": 3868 if a["k"] == "sgpr":
3643 if self.holds_lane_mask(a): 3869 if self.holds_lane_mask(a):
3870 if self.wave64 and wide and a.get("n") == 2:
3871 lo, hi = self.load_reg("sgpr", a["r"]), self.load_reg("sgpr", a["r"] + 1)
3872 up, sel = self.tmp(), self.tmp()
3873 self.emit(f"{up} = OpUGreaterThanEqual %bool {self.wave_lane()} {self.cu(32)}")
3874 self.emit(f"{sel} = OpSelect %uint {up} {hi} {lo}")
3875 return sel
3644 return self.load_reg("sgpr", a["r"]) 3876 return self.load_reg("sgpr", a["r"])
3645 # Not known to hold a mask: the SGPR may hold a constant (s_mov_b32 s20, 0x3ffffc00) that is the same in 3877 # Not known to hold a mask: the SGPR may hold a constant (s_mov_b32 s20, 0x3ffffc00) that is the same in
3646 # every invocation, so lane L takes its bit L, as for an immediate. Until 2026-11-22 the raw value was used 3878 # every invocation, so lane L takes its bit L, as for an immediate. Until 2026-11-22 the raw value was used
@@ -3660,6 +3892,8 @@ class Gen:
3660 self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}") 3892 self.emit(f"{bit} = OpBitwiseAnd %uint {shr} {self.cu(1)}")
3661 self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") 3893 self.emit(f"{r} = OpSelect %uint {self.tmp_bool_nz(bit)} {self.cu(0xFFFFFFFF)} {self.cu(0)}")
3662 return r 3894 return r
3895 if a["k"] == "special" and a["t"] == "null":
3896 return self.cu(0)
3663 if a["k"] == "special" and a["t"] in ("vcc", "vcc_lo", "vcc_hi"): 3897 if a["k"] == "special" and a["t"] in ("vcc", "vcc_lo", "vcc_hi"):
3664 v = self.tmp() 3898 v = self.tmp()
3665 self.emit(f"{v} = OpLoad %uint %vcc") 3899 self.emit(f"{v} = OpLoad %uint %vcc")
@@ -3815,6 +4049,18 @@ class Gen:
3815 self.emit(f"{arg} = OpFMul %float {t} {self.fconst(6.283185307179586)}") 4049 self.emit(f"{arg} = OpFMul %float {t} {self.fconst(6.283185307179586)}")
3816 return arg 4050 return arg
3817 4051
4052 def trig_exact_zero(self, op, x, r):
4053 """v_sin/v_cos: +0 where the hardware gives an exact zero, i.e. sin at an odd half turn and cos at an odd quarter
4054 turn (|x - RoundEven(x)| is 0.5 or 0.25). Sin(2*pi*0.5) with a rounded 2*pi is about -8.7e-8 instead. Measured
4055 natively on gfx1036 for f32 and f16, both signs, from 0.25 up to 2^22 turns (SHADER-134)."""
4056 rnd, d, ad, hit, out = (self.tmp() for _ in range(5))
4057 self.emit(f"{rnd} = OpExtInst %float %glsl RoundEven {x}")
4058 self.emit(f"{d} = OpFSub %float {x} {rnd}")
4059 self.emit(f"{ad} = OpExtInst %float %glsl FAbs {d}")
4060 self.emit(f"{hit} = OpFOrdEqual %bool {ad} {self.fconst(0.5 if 'sin' in op else 0.25)}")
4061 self.emit(f"{out} = OpSelect %float {hit} %f0 {r}")
4062 return out
4063
3818 def fconst(self, x): 4064 def fconst(self, x):
3819 bits = struct.unpack("<I", struct.pack("<f", x))[0] 4065 bits = struct.unpack("<I", struct.pack("<f", x))[0]
3820 return self.tof(self.cu(bits)) 4066 return self.tof(self.cu(bits))
@@ -3827,6 +4073,36 @@ class Gen:
3827 self.emit(f"{d} = OpBitcast %double {v2}") 4073 self.emit(f"{d} = OpBitcast %double {v2}")
3828 return d 4074 return d
3829 4075
4076 def round_f32_flushed(self, fn, x):
4077 """v_floor_f32 / v_ceil_f32 / v_fract_f32 of the operand x (source modifiers applied) as RDNA2 computes them in
4078 the MODE inferred for the game (IEEE 0, f32 denormals flushed), measured natively on gfx1036: a denormal
4079 operand is a zero of its sign (floor(-1e-45) = -0, ceil(+1e-45) = +0, fract of either 0; using the denormal
4080 gives -1.0, +1.0 and 0x3f7fffff), and a NaN operand passes through unchanged (signalling ones too).
4081 fract(+-inf) is the negative quiet NaN 0xffc00000. Done here rather than left to the driver's f32 denormal
4082 handling, which Vulkan does not fix."""
4083 bits, mag, exp, den, sgn, sz, xf, r = (self.tmp() for _ in range(8))
4084 self.emit(f"{bits} = OpBitcast %uint {x}")
4085 self.emit(f"{mag} = OpBitwiseAnd %uint {bits} {self.cu(0x7FFFFFFF)}")
4086 self.emit(f"{exp} = OpBitwiseAnd %uint {bits} {self.cu(0x7F800000)}")
4087 self.emit(f"{den} = OpIEqual %bool {exp} {self.cu(0)}")
4088 self.emit(f"{sgn} = OpBitwiseAnd %uint {bits} {self.cu(0x80000000)}")
4089 self.emit(f"{sz} = OpSelect %uint {den} {sgn} {bits}")
4090 self.emit(f"{xf} = OpBitcast %float {sz}")
4091 self.emit(f"{r} = OpExtInst %float %glsl {fn} {xf}")
4092 if fn == "Fract":
4093 r = self.fract_below_one(r)
4094 nan, inf, rb, keep, out = (self.tmp() for _ in range(5))
4095 self.emit(f"{rb} = OpBitcast %uint {r}")
4096 self.emit(f"{nan} = OpUGreaterThan %bool {mag} {self.cu(0x7F800000)}")
4097 self.emit(f"{keep} = OpSelect %uint {nan} {bits} {rb}")
4098 if fn == "Fract":
4099 fixed = self.tmp()
4100 self.emit(f"{inf} = OpIEqual %bool {mag} {self.cu(0x7F800000)}")
4101 self.emit(f"{fixed} = OpSelect %uint {inf} {self.cu(0xFFC00000)} {keep}")
4102 keep = fixed
4103 self.emit(f"{out} = OpBitcast %float {keep}")
4104 return out
4105
3830 def fract_below_one(self, r): 4106 def fract_below_one(self, r):
3831 """v_fract: a Fract(x) that rounded up to 1.0 (x a tiny negative number) becomes 0x3f7fffff, the largest 4107 """v_fract: a Fract(x) that rounded up to 1.0 (x a tiny negative number) becomes 0x3f7fffff, the largest
3832 float below 1, as on hardware. A compare and select, not FMin, so the NaN of fract(+-inf) is kept.""" 4108 float below 1, as on hardware. A compare and select, not FMin, so the NaN of fract(+-inf) is kept."""
@@ -3892,6 +4168,7 @@ class Gen:
3892 self.cur_uniform_readlane = bool(self.w64g) and id(ins) in self.w64g["uniform_readlane"] 4168 self.cur_uniform_readlane = bool(self.w64g) and id(ins) in self.w64g["uniform_readlane"]
3893 if self.emulate: 4169 if self.emulate:
3894 self.x_memory_order(base_op(ins["op"])) 4170 self.x_memory_order(base_op(ins["op"]))
4171 self.cur_either = self.lane_either.get(id(ins), ())
3895 if ins["op"].endswith("_dpp"): 4172 if ins["op"].endswith("_dpp"):
3896 return self.dpp_insn(ins) 4173 return self.dpp_insn(ins)
3897 if not ins["op"].endswith("_sdwa"): 4174 if not ins["op"].endswith("_sdwa"):
@@ -4408,6 +4685,7 @@ class Gen:
4408 f = self.modify_f(f, a[1]) 4685 f = self.modify_f(f, a[1])
4409 t = self.turn_angle(f) 4686 t = self.turn_angle(f)
4410 self.emit(f"{r} = OpExtInst %float %glsl {'Sin' if 'sin' in op else 'Cos'} {t}") 4687 self.emit(f"{r} = OpExtInst %float %glsl {'Sin' if 'sin' in op else 'Cos'} {t}")
4688 r = self.trig_exact_zero(op, f, r)
4411 r = self.clamp_mods(r, mods) 4689 r = self.clamp_mods(r, mods)
4412 self.write_lo16(a[0], self.f16_bits(r)) # sin ignores MODE rounding on hardware (RX 6800, SHADER-35); cos is unmeasured, assumed like it 4690 self.write_lo16(a[0], self.f16_bits(r)) # sin ignores MODE rounding on hardware (RX 6800, SHADER-35); cos is unmeasured, assumed like it
4413 elif op in ("v_pk_add_u16", "v_pk_add_i16", "v_pk_sub_u16", "v_pk_sub_i16", "v_pk_mul_lo_u16", 4691 elif op in ("v_pk_add_u16", "v_pk_add_i16", "v_pk_sub_u16", "v_pk_sub_i16", "v_pk_mul_lo_u16",
@@ -4571,6 +4849,7 @@ class Gen:
4571 t = self.turn_angle(x) 4849 t = self.turn_angle(x)
4572 r = self.tmp() 4850 r = self.tmp()
4573 self.emit(f"{r} = OpExtInst %float %glsl {'Sin' if 'sin' in op else 'Cos'} {t}") 4851 self.emit(f"{r} = OpExtInst %float %glsl {'Sin' if 'sin' in op else 'Cos'} {t}")
4852 r = self.trig_exact_zero(op, x, r)
4574 self.dst(a[0], self.tou(self.clamp_mods(r, mods))) 4853 self.dst(a[0], self.tou(self.clamp_mods(r, mods)))
4575 elif op == "v_rndne_f32": 4854 elif op == "v_rndne_f32":
4576 x = self.src_f(a[1]) 4855 x = self.src_f(a[1])
@@ -4615,9 +4894,10 @@ class Gen:
4615 elif op == "v_pack_b32_f16": 4894 elif op == "v_pack_b32_f16":
4616 # dst = f16(src0) | f16(src1) << 16, each taken from the low half (op_sel picks high halves). 4895 # dst = f16(src0) | f16(src1) << 16, each taken from the low half (op_sel picks high halves).
4617 # neg/abs act on the selected 16-bit half of each source as plain bit moves, abs (clear bit 15) first and 4896 # neg/abs act on the selected 16-bit half of each source as plain bit moves, abs (clear bit 15) first and
4618 # neg (xor bit 15) second: on a Radeon 680M (gfx1036) ``-v0`` turned 0x7c01 into 0xfc01 under IEEE 0 and 4897 # neg (xor bit 15) second: on an AMD Radeon Graphics RDNA2 iGPU (gfx1036) ``-v0``, ``|v0|``, and ``-|v0|``
4619 # 0xfe01 under IEEE 1, in either half and with op_sel (#1548 SHADER-260). abs rests on the ISA's sign 4898 # were measured with 1,088 raw kernels across wave32 and wave64 (0 mismatches; #1548 SHADER-260). abs clears
4620 # clear, it was not measured on this instruction. Only the IEEE 1 sNaN quieting is open (SHADER-190). 4899 # bit 15, neg flips it, and -|v0| sets bit 15 across all edge floats and NaNs; under IEEE 0 sNaN payloads are
4900 # kept, under IEEE 1 they are quieted (SHADER-190). The translator moves the bits, which is exact under IEEE 0.
4621 sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]") 4901 sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]")
4622 sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] 4902 sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")]
4623 halves = [] 4903 halves = []
@@ -4630,8 +4910,8 @@ class Gen:
4630 m = self.tmp() 4910 m = self.tmp()
4631 self.emit(f"{m} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}") 4911 self.emit(f"{m} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}")
4632 if src.get("abs"): 4912 if src.get("abs"):
4633 # The ISA defines ABS on a float operand as |S|, a clear of the sign bit, and it is applied before 4913 # The ISA defines ABS on a float operand as |S|, clearing the sign bit (bit 15), applied before
4634 # neg; no hardware run of this instruction with `abs` exists yet. 4914 # neg. Measured natively on gfx1036 across 1,088 raw kernels: clears bit 15 on all values.
4635 a_ = self.tmp() 4915 a_ = self.tmp()
4636 self.emit(f"{a_} = OpBitwiseAnd %uint {m} {self.cu(0x7FFF)}") 4916 self.emit(f"{a_} = OpBitwiseAnd %uint {m} {self.cu(0x7FFF)}")
4637 m = a_ 4917 m = a_
@@ -4725,7 +5005,9 @@ class Gen:
4725 # Count of set bits in the mask for lanes below this one (lo: lanes 0-31, hi: lanes 32-63), plus src1. 5005 # Count of set bits in the mask for lanes below this one (lo: lanes 0-31, hi: lanes 32-63), plus src1.
4726 self.uses_subgroup = True 5006 self.uses_subgroup = True
4727 if self.holds_lane_mask(a[1]): # a real mask: the lanes below this one that are set in it 5007 if self.holds_lane_mask(a[1]): # a real mask: the lanes below this one that are set in it
4728 mask = self.wave_mask(a[1])[0 if op.endswith("lo_u32_b32") else 1] 5008 half = self.mask_half(a[1]) if self.wave64 else None
5009 idx = (1 if half == "hi" else 0) if half is not None else (0 if op.endswith("lo_u32_b32") else 1)
5010 mask = self.wave_mask(a[1])[idx]
4729 acc = self.src_u(a[2]) 5011 acc = self.src_u(a[2])
4730 else: 5012 else:
4731 mask, acc = self.src_u(a[1]), self.src_u(a[2]) 5013 mask, acc = self.src_u(a[1]), self.src_u(a[2])
@@ -4925,14 +5207,16 @@ class Gen:
4925 self.dst(a[0], r) 5207 self.dst(a[0], r)
4926 elif op == "ds_swizzle_b32": 5208 elif op == "ds_swizzle_b32":
4927 self.swizzle(a, mods, ins) 5209 self.swizzle(a, mods, ins)
4928 elif op in ("v_add_f64", "v_cvt_f32_f64"): 5210 elif op in ("v_add_f64", "v_cvt_f32_f64", "v_rcp_f64", "v_rsq_f64", "v_sqrt_f64"):
4929 # f64: register pairs as doubles (shaderFloat64). neg/abs modifiers apply to the double. 5211 # f64: register pairs as doubles (shaderFloat64). neg/abs modifiers apply to the double.
4930 def f64(sv): 5212 def f64(sv):
4931 if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2: 5213 if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2:
4932 lo, hi = self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1) 5214 lo, hi = self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1)
4933 elif sv["k"] == "imm" or sv["k"] == "fimm": 5215 elif sv.get("f64_literal"):
4934 import struct as _st 5216 lo, hi = self.cu(0), self.cu(sv["v"] & 0xFFFFFFFF)
4935 bits = _st.unpack("<Q", _st.pack("<d", float(sv["v"])))[0] if sv["k"] == "fimm" else sv["v"] & 0xFFFFFFFFFFFFFFFF 5217 elif sv["k"] in ("imm", "fimm"):
5218 bits = (struct.unpack("<Q", struct.pack("<d", sv["v"]))[0]
5219 if sv["k"] == "fimm" else sv["v"] & 0xFFFFFFFFFFFFFFFF)
4936 lo, hi = self.cu(bits & 0xFFFFFFFF), self.cu(bits >> 32) 5220 lo, hi = self.cu(bits & 0xFFFFFFFF), self.cu(bits >> 32)
4937 else: 5221 else:
4938 raise Unsupported(op + " operand") 5222 raise Unsupported(op + " operand")
@@ -4949,22 +5233,41 @@ class Gen:
4949 d = t 5233 d = t
4950 return d 5234 return d
4951 self.uses_f64 = True 5235 self.uses_f64 = True
4952 if op == "v_add_f64": 5236 if op == "v_cvt_f32_f64":
4953 x, y = f64(a[1]), f64(a[2]) 5237 x = f64(a[1])
4954 r, v2, lo, hi = self.tmp(), self.tmp(), self.tmp(), self.tmp() 5238 r = self.tmp()
4955 self.emit(f"{r} = OpFAdd %double {x} {y}") 5239 self.emit(f"{r} = OpFConvert %float {x}")
4956 if self.round_mode: 5240 self.dst(a[0], self.tou(self.clamp_mods(r, mods)))
4957 # MODE rounds the sum itself; clamp/omod then apply to the rounded value, as on the hardware. 5241 else:
4958 m2, mlo, mhi, n2, rd = (self.tmp() for _ in range(5)) 5242 if op == "v_add_f64":
4959 self.emit(f"{m2} = OpBitcast %v2uint_d {r}") 5243 x, y = f64(a[1]), f64(a[2])
4960 self.emit(f"{mlo} = OpCompositeExtract %uint {m2} 0") 5244 r = self.tmp()
4961 self.emit(f"{mhi} = OpCompositeExtract %uint {m2} 1") 5245 self.emit(f"{r} = OpFAdd %double {x} {y}")
4962 mlo, mhi = self.f64_add_mode(x, y, r, mlo, mhi) 5246 if self.round_mode:
4963 self.emit(f"{n2} = OpCompositeConstruct %v2uint_d {mlo} {mhi}") 5247 # MODE rounds the sum itself; clamp/omod then apply to the rounded value, as on the hardware.
4964 self.emit(f"{rd} = OpBitcast %double {n2}") 5248 m2, mlo, mhi, n2, rd = (self.tmp() for _ in range(5))
4965 r = rd 5249 self.emit(f"{m2} = OpBitcast %v2uint_d {r}")
4966 # VOP3_Profile<VOP_F64_F64_F64>: HasClamp and HasOMod (LLVM VOPProfile, f64 is a modifier type). 5250 self.emit(f"{mlo} = OpCompositeExtract %uint {m2} 0")
5251 self.emit(f"{mhi} = OpCompositeExtract %uint {m2} 1")
5252 mlo, mhi = self.f64_add_mode(x, y, r, mlo, mhi)
5253 self.emit(f"{n2} = OpCompositeConstruct %v2uint_d {mlo} {mhi}")
5254 self.emit(f"{rd} = OpBitcast %double {n2}")
5255 r = rd
5256 elif op == "v_rcp_f64":
5257 x = f64(a[1])
5258 r = self.tmp()
5259 self.emit(f"{r} = OpFDiv %double {self.dconst(1.0)} {x}")
5260 elif op == "v_rsq_f64":
5261 x = f64(a[1])
5262 r = self.tmp()
5263 self.emit(f"{r} = OpExtInst %double %glsl InverseSqrt {x}")
5264 else: # v_sqrt_f64
5265 x = f64(a[1])
5266 r = self.tmp()
5267 self.emit(f"{r} = OpExtInst %double %glsl Sqrt {x}")
5268 # VOP3 f64 ops carry HasClamp and HasOMod (LLVM VOPProfile, f64 is a modifier type).
4967 r = self.clamp_mods_f64(r, mods) 5269 r = self.clamp_mods_f64(r, mods)
5270 v2, lo, hi = self.tmp(), self.tmp(), self.tmp()
4968 self.emit(f"{v2} = OpBitcast %v2uint_d {r}") 5271 self.emit(f"{v2} = OpBitcast %v2uint_d {r}")
4969 self.emit(f"{lo} = OpCompositeExtract %uint {v2} 0") 5272 self.emit(f"{lo} = OpCompositeExtract %uint {v2} 0")
4970 self.emit(f"{hi} = OpCompositeExtract %uint {v2} 1") 5273 self.emit(f"{hi} = OpCompositeExtract %uint {v2} 1")
@@ -4973,11 +5276,6 @@ class Gen:
4973 raise Unsupported(op + " destination") 5276 raise Unsupported(op + " destination")
4974 self.dst({"k": "vgpr", "r": d["r"], "n": 1}, lo) 5277 self.dst({"k": "vgpr", "r": d["r"], "n": 1}, lo)
4975 self.dst({"k": "vgpr", "r": d["r"] + 1, "n": 1}, hi) 5278 self.dst({"k": "vgpr", "r": d["r"] + 1, "n": 1}, hi)
4976 else:
4977 x = f64(a[1])
4978 r = self.tmp()
4979 self.emit(f"{r} = OpFConvert %float {x}")
4980 self.dst(a[0], self.tou(self.clamp_mods(r, mods)))
4981 elif op in ("image_bvh_intersect_ray", "image_bvh64_intersect_ray"): 5279 elif op in ("image_bvh_intersect_ray", "image_bvh64_intersect_ray"):
4982 self.image_bvh(op, a, mods) 5280 self.image_bvh(op, a, mods)
4983 elif op == "s_bfm_b64": 5281 elif op == "s_bfm_b64":
@@ -6676,9 +6974,9 @@ class Gen:
6676 self.emit(f"{rlo} = OpSelect %uint {b} {xlo} {oldlo}") 6974 self.emit(f"{rlo} = OpSelect %uint {b} {xlo} {oldlo}")
6677 self.emit(f"{rhi} = OpSelect %uint {b} {xhi} {oldhi}") 6975 self.emit(f"{rhi} = OpSelect %uint {b} {xhi} {oldhi}")
6678 self.dst64_data(a[0], rlo, rhi, op) 6976 self.dst64_data(a[0], rlo, rhi, op)
6679 elif op.startswith("v_cmp_") and not op.startswith("v_cmp_class") and not op.endswith(("_u64", "_i64")): 6977 elif op.startswith("v_cmp_") and not op.startswith("v_cmp_class"):
6680 self.compare(op, a, scalar=False, mods=mods) 6978 self.compare(op, a, scalar=False, mods=mods)
6681 elif op.startswith("v_cmpx_") and not op.startswith("v_cmpx_class") and not op.endswith(("_u64", "_i64")): 6979 elif op.startswith("v_cmpx_") and not op.startswith("v_cmpx_class"):
6682 self.compare_x(op, a, mods=mods) 6980 self.compare_x(op, a, mods=mods)
6683 elif op.endswith(("_saveexec_b64", "_saveexec_b32")) and op[2:].split("_saveexec")[0] in self.EXEC_LOGIC: 6981 elif op.endswith(("_saveexec_b64", "_saveexec_b32")) and op[2:].split("_saveexec")[0] in self.EXEC_LOGIC:
6684 # RDNA2 ISA SOP1: D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0). One invocation holds its own lane's bit 6982 # RDNA2 ISA SOP1: D = EXEC; EXEC = f(S0, EXEC); SCC = (EXEC != 0). One invocation holds its own lane's bit
@@ -7060,10 +7358,10 @@ class Gen:
7060 r = self.tmp() 7358 r = self.tmp()
7061 if F1[op] == "rcp": 7359 if F1[op] == "rcp":
7062 self.emit(f"{r} = OpFDiv %float %f1 {x}") 7360 self.emit(f"{r} = OpFDiv %float %f1 {x}")
7361 elif F1[op] in ("Floor", "Ceil", "Fract"):
7362 r = self.round_f32_flushed(F1[op], x)
7063 else: 7363 else:
7064 self.emit(f"{r} = OpExtInst %float %glsl {F1[op]} {x}") 7364 self.emit(f"{r} = OpExtInst %float %glsl {F1[op]} {x}")
7065 if F1[op] == "Fract":
7066 r = self.fract_below_one(r)
7067 self.dst(a[0], self.tou(self.clamp_mods(r, mods))) 7365 self.dst(a[0], self.tou(self.clamp_mods(r, mods)))
7068 elif op in ("v_frexp_mant_f32", "v_frexp_exp_i32_f32", "v_ldexp_f32"): 7366 elif op in ("v_frexp_mant_f32", "v_frexp_exp_i32_f32", "v_ldexp_f32"):
7069 # Bit-exact on the binary32 word (no float arithmetic). A normal input has biased exponent 1..254; 7367 # Bit-exact on the binary32 word (no float arithmetic). A normal input has biased exponent 1..254;
@@ -7120,6 +7418,63 @@ class Gen:
7120 self.emit(f"{scaled} = OpSelect %uint {valid} {norm} {ov}") 7418 self.emit(f"{scaled} = OpSelect %uint {valid} {norm} {ov}")
7121 self.emit(f"{r} = OpSelect %uint {isnorm} {scaled} {other}") 7419 self.emit(f"{r} = OpSelect %uint {isnorm} {scaled} {other}")
7122 self.dst(a[0], self.tou(self.clamp_mods(self.tof(r), mods))) 7420 self.dst(a[0], self.tou(self.clamp_mods(self.tof(r), mods)))
7421 elif op in ("v_frexp_mant_f64", "v_frexp_exp_i32_f64"):
7422 # Binary64 version of v_frexp_mant_f32 / v_frexp_exp_i32_f32, bit-exact on the (lo, hi) dword pair.
7423 # Normal inputs have biased exponent 1..2046; zero and denormals give +-0 / exp 0, infinities and NaNs
7424 # pass through unchanged / exp 0 (RDNA2 ISA, V_FREXP_MANT_F64 / V_FREXP_EXP_I32_F64).
7425 sv = a[1]
7426 if sv["k"] in ("vgpr", "sgpr") and sv.get("n") == 2:
7427 lo, hi = self.load_reg(sv["k"], sv["r"]), self.load_reg(sv["k"], sv["r"] + 1)
7428 elif sv["k"] in ("imm", "fimm"):
7429 bits = (struct.unpack("<Q", struct.pack("<d", float(sv["v"])))[0]
7430 if sv["k"] == "fimm" else sv["v"] & 0xFFFFFFFFFFFFFFFF)
7431 lo, hi = self.cu(bits & 0xFFFFFFFF), self.cu(bits >> 32)
7432 else:
7433 raise Unsupported(op + " operand")
7434 if sv.get("abs"):
7435 t = self.tmp()
7436 self.emit(f"{t} = OpBitwiseAnd %uint {hi} {self.cu(0x7FFFFFFF)}")
7437 hi = t
7438 if sv.get("neg"):
7439 t = self.tmp()
7440 self.emit(f"{t} = OpBitwiseXor %uint {hi} {self.cu(0x80000000)}")
7441 hi = t
7442 e, em1, isnorm, isden, sgn = (self.tmp() for _ in range(5))
7443 self.emit(f"{e} = OpBitFieldUExtract %uint {hi} {self.cu(20)} {self.cu(11)}")
7444 self.emit(f"{em1} = OpISub %uint {e} {self.cu(1)}")
7445 self.emit(f"{isnorm} = OpULessThan %bool {em1} {self.cu(2046)}") # exponent field 1..2046
7446 self.emit(f"{isden} = OpIEqual %bool {e} {self.cu(0)}")
7447 self.emit(f"{sgn} = OpBitwiseAnd %uint {hi} {self.cu(0x80000000)}")
7448 if op == "v_frexp_exp_i32_f64":
7449 if any(m in ("clamp", "mul:2", "mul:4", "div:2") for m in mods):
7450 raise Unsupported(op + " output modifier")
7451 ex, r = self.tmp(), self.tmp()
7452 self.emit(f"{ex} = OpISub %uint {e} {self.cu(1022)}")
7453 self.emit(f"{r} = OpSelect %uint {isnorm} {ex} {self.cu(0)}")
7454 self.dst(a[0], r)
7455 else:
7456 d = a[0]
7457 if d["k"] != "vgpr" or d.get("n") != 2:
7458 raise Unsupported(op + " destination")
7459 keep, m_hi, other_hi, other_lo, r_hi, r_lo = (self.tmp() for _ in range(6))
7460 self.emit(f"{keep} = OpBitwiseAnd %uint {hi} {self.cu(0x800FFFFF)}")
7461 self.emit(f"{m_hi} = OpBitwiseOr %uint {keep} {self.cu(0x3FE00000)}") # biased exponent 1022
7462 self.emit(f"{other_hi} = OpSelect %uint {isden} {sgn} {hi}")
7463 self.emit(f"{other_lo} = OpSelect %uint {isden} {self.cu(0)} {lo}")
7464 self.emit(f"{r_hi} = OpSelect %uint {isnorm} {m_hi} {other_hi}")
7465 self.emit(f"{r_lo} = OpSelect %uint {isnorm} {lo} {other_lo}")
7466 if any(m in ("clamp", "mul:2", "mul:4", "div:2") for m in mods):
7467 self.uses_f64 = True
7468 v2, dv, mv2 = self.tmp(), self.tmp(), self.tmp()
7469 self.emit(f"{v2} = OpCompositeConstruct %v2uint_d {r_lo} {r_hi}")
7470 self.emit(f"{dv} = OpBitcast %double {v2}")
7471 dv = self.clamp_mods_f64(dv, mods)
7472 self.emit(f"{mv2} = OpBitcast %v2uint_d {dv}")
7473 r_lo, r_hi = self.tmp(), self.tmp()
7474 self.emit(f"{r_lo} = OpCompositeExtract %uint {mv2} 0")
7475 self.emit(f"{r_hi} = OpCompositeExtract %uint {mv2} 1")
7476 self.dst({"k": "vgpr", "r": d["r"], "n": 1}, r_lo)
7477 self.dst({"k": "vgpr", "r": d["r"] + 1, "n": 1}, r_hi)
7123 elif op in ("v_cvt_f32_u32", "v_cvt_f32_i32"): 7478 elif op in ("v_cvt_f32_u32", "v_cvt_f32_i32"):
7124 x = self.src_u(a[1]) 7479 x = self.src_u(a[1])
7125 r = self.tmp() 7480 r = self.tmp()
@@ -7149,8 +7504,14 @@ class Gen:
7149 self.emit(f"{x_in_range} = OpULessThan %bool {x_mag} {self.cu(0x4F000000)}") # |x| < 2^31 7504 self.emit(f"{x_in_range} = OpULessThan %bool {x_mag} {self.cu(0x4F000000)}") # |x| < 2^31
7150 self.emit(f"{x_neg} = OpINotEqual %bool {x_bits} {x_mag}") 7505 self.emit(f"{x_neg} = OpINotEqual %bool {x_bits} {x_mag}")
7151 self.emit(f"{bound} = OpSelect %uint {x_neg} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}") 7506 self.emit(f"{bound} = OpSelect %uint {x_neg} {self.cu(0x80000000)} {self.cu(0x7FFFFFFF)}")
7152 # Guard before Floor/FSub/FToS: -2^31 (0xCF000000) takes `bound` = 0x80000000 directly. 7507 # Guard before Floor/FSub/FToS: -2^31 (0xCF000000) takes `bound` = 0x80000000 directly. A denormal operand
7153 self.emit(f"{safe_x_u} = OpSelect %uint {x_in_range} {x_bits} {self.cu(0)}") 7508 # is a zero, as on RDNA2 with f32 denormals flushed (the MODE inferred for the game; gfx1036 gives
7509 # flr(-1e-45) = 0, where Floor of the kept denormal gives -1).
7510 x_exp, x_norm, keep_x = self.tmp(), self.tmp(), self.tmp()
7511 self.emit(f"{x_exp} = OpBitwiseAnd %uint {x_bits} {self.cu(0x7F800000)}")
7512 self.emit(f"{x_norm} = OpINotEqual %bool {x_exp} {self.cu(0)}")
7513 self.emit(f"{keep_x} = OpLogicalAnd %bool {x_in_range} {x_norm}")
7514 self.emit(f"{safe_x_u} = OpSelect %uint {keep_x} {x_bits} {self.cu(0)}")
7154 safe_x = self.tof(safe_x_u) 7515 safe_x = self.tof(safe_x_u)
7155 self.emit(f"{fl} = OpExtInst %float %glsl Floor {safe_x}") 7516 self.emit(f"{fl} = OpExtInst %float %glsl Floor {safe_x}")
7156 if op == "v_cvt_rpi_i32_f32": 7517 if op == "v_cvt_rpi_i32_f32":
@@ -7694,7 +8055,7 @@ class Gen:
7694 gather_border); a literal S# with a half-border mode (4, 5), or that sets FORCE_UNNORMALIZED, is Unsupported: 8055 gather_border); a literal S# with a half-border mode (4, 5), or that sets FORCE_UNNORMALIZED, is Unsupported:
7695 the four fetches can't reproduce it. A run-time S# can't be judged at translation time, so modes 4 and 5 are 8056 the four fetches can't reproduce it. A run-time S# can't be judged at translation time, so modes 4 and 5 are
7696 treated as clamp-to-edge there, and FORCE_UNNORMALIZED (bit 15) is not applied (the two remaining 8057 treated as clamp-to-edge there, and FORCE_UNNORMALIZED (bit 15) is not applied (the two remaining
7697 approximations).""" 8058 approximations, with gather_border_one's table colour at run time)."""
7698 if s_op["k"] != "sgpr" or s_op.get("n", 1) < 4: 8059 if s_op["k"] != "sgpr" or s_op.get("n", 1) < 4:
7699 raise Unsupported("descriptor operand") 8060 raise Unsupported("descriptor operand")
7700 lit = self.sgpr_imm.get(s_op["r"]) 8061 lit = self.sgpr_imm.get(s_op["r"])
@@ -9783,6 +10144,12 @@ def assemble(gen):
9783 caps.append("ShaderLayer") 10144 caps.append("ShaderLayer")
9784 if gen.uses_viewport: 10145 if gen.uses_viewport:
9785 caps.append("ShaderViewportIndex") 10146 caps.append("ShaderViewportIndex")
10147 if FLOAT_CONTROLS:
10148 # RDNA2 float ops are IEEE: NaN, +-inf and -0 come out as computed. Without this execution mode Vulkan lets
10149 # the driver assume none of them occur, and AMD's compiler does: a -0 product came back +0, and a NaN result
10150 # narrowed to f16 with integer ops was never stored (RX 9070 XT; docs/design.md, "Float controls").
10151 # Core in SPIR-V 1.4, so no extension at vulkan1.2; the runtime checks shaderSignedZeroInfNanPreserveFloat32.
10152 caps.append("SignedZeroInfNanPreserve")
9786 pops = gen.uses_pops and gen.stage == "ps" 10153 pops = gen.uses_pops and gen.stage == "ps"
9787 exts = (["SPV_KHR_physical_storage_buffer"] if psb else []) + (["SPV_EXT_descriptor_indexing"] if tex else []) 10154 exts = (["SPV_KHR_physical_storage_buffer"] if psb else []) + (["SPV_EXT_descriptor_indexing"] if tex else [])
9788 if gen.uses_fma_khr: 10155 if gen.uses_fma_khr:
@@ -9816,6 +10183,8 @@ def assemble(gen):
9816 hdr.append("OpExecutionMode %main PixelInterlockOrderedEXT") 10183 hdr.append("OpExecutionMode %main PixelInterlockOrderedEXT")
9817 if gen.writes_depth: 10184 if gen.writes_depth:
9818 hdr.append("OpExecutionMode %main DepthReplacing") 10185 hdr.append("OpExecutionMode %main DepthReplacing")
10186 if FLOAT_CONTROLS:
10187 hdr.append("OpExecutionMode %main SignedZeroInfNanPreserve 32")
9819 dec = [] 10188 dec = []
9820 if vs: 10189 if vs:
9821 dec.append("OpDecorate %vertex_index BuiltIn VertexIndex") 10190 dec.append("OpDecorate %vertex_index BuiltIn VertexIndex")
@@ -11981,6 +12350,9 @@ def shader_meta(g, asm, src_path=None, fssm_path=None):
11981 m["subgroup_size"] = None 12350 m["subgroup_size"] = None
11982 if "Offset " in asm and re.search(r"OpImageSample\w+ [^\n]*Offset", asm): 12351 if "Offset " in asm and re.search(r"OpImageSample\w+ [^\n]*Offset", asm):
11983 m["needs_maintenance8"] = True 12352 m["needs_maintenance8"] = True
12353 if "SignedZeroInfNanPreserve" in caps:
12354 # A property, not a feature: VkPhysicalDeviceFloatControlsProperties members the device must report true.
12355 m["float_controls"] = ["shaderSignedZeroInfNanPreserveFloat32"]
11984 if g.uses_codebase: 12356 if g.uses_codebase:
11985 m["uses_code_base"] = True 12357 m["uses_code_base"] = True
11986 if g.cs: 12358 if g.cs:
@@ -12181,13 +12553,27 @@ def merge_shard_parts(out):
12181 return merged 12553 return merged
12182 12554
12183 12555
12184def assemble_spirv(sa, sv): 12556def assemble_spirv(sa, sv, asm_text=None, assembler="spirv-as"):
12185 """Keep the assembled module out of the final path until validation succeeds.""" 12557 """Keep the assembled module out of the final path until validation succeeds.
12558
12559 `assembler="spirv-as"` invokes the external spirv-as binary on `sa` (default);
12560 `assembler="python"` encodes `asm_text` (or reads `sa`) directly in memory with
12561 tools/spirv_asm.py, avoiding the spirv-as subprocess and temporary .spvasm I/O.
12562 """
12186 with tempfile.NamedTemporaryFile(prefix=".spirv-", suffix=".tmp", dir=os.path.dirname(sv), delete=False) as f: 12563 with tempfile.NamedTemporaryFile(prefix=".spirv-", suffix=".tmp", dir=os.path.dirname(sv), delete=False) as f:
12187 tmp = Path(f.name) 12564 tmp = Path(f.name)
12188 try: 12565 try:
12189 result = subprocess.run(["spirv-as", sa, "-o", str(tmp), "--target-env", "vulkan1.2"], 12566 if assembler == "python":
12190 capture_output=True, text=True) 12567 import spirv_asm
12568 try:
12569 text = asm_text if asm_text is not None else Path(sa).read_text(encoding="utf-8")
12570 tmp.write_bytes(spirv_asm.assemble(text, target_env="vulkan1.2"))
12571 result = subprocess.CompletedProcess(["spirv_asm"], 0, "", "")
12572 except (OSError, spirv_asm.SpirvAsmError) as exc:
12573 result = subprocess.CompletedProcess(["spirv_asm"], 1, "", str(exc))
12574 else:
12575 result = subprocess.run(["spirv-as", sa, "-o", str(tmp), "--target-env", "vulkan1.2"],
12576 capture_output=True, text=True)
12191 if result.returncode == 0: 12577 if result.returncode == 0:
12192 # Offset on non-gather: VK_KHR_maintenance8 12578 # Offset on non-gather: VK_KHR_maintenance8
12193 result = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", "--allow-offset-texture-operand", 12579 result = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", "--allow-offset-texture-operand",
@@ -12234,11 +12620,17 @@ def main():
12234 "then merge the index.part*.json files with --merge)") 12620 "then merge the index.part*.json files with --merge)")
12235 ap.add_argument("--no-asm", action="store_true", 12621 ap.add_argument("--no-asm", action="store_true",
12236 help="delete each .spvasm once its .spv is written (the text is ~2.7x the binary: 35 GB for the corpus)") 12622 help="delete each .spvasm once its .spv is written (the text is ~2.7x the binary: 35 GB for the corpus)")
12623 ap.add_argument("--assembler", choices=("spirv-as", "python"), default="spirv-as",
12624 help="SPIR-V binary assembler: spirv-as (default, external binary) or python (in-process "
12625 "tools/spirv_asm.py; skips writing .spvasm to disk when combined with --no-asm)")
12237 ap.add_argument("--merge", action="store_true", help="merge index.part*.json in --out into index.json and exit") 12626 ap.add_argument("--merge", action="store_true", help="merge index.part*.json in --out into index.json and exit")
12238 ap.add_argument("--fssm-dir", default=None, 12627 ap.add_argument("--fssm-dir", default=None,
12239 help="optional dir with <name>.fssm sidecars: records fssm_sha256 per shader in the index") 12628 help="optional dir with <name>.fssm sidecars: records fssm_sha256 per shader in the index")
12240 ap.add_argument("--dispatch-loop", action="store_true", 12629 ap.add_argument("--dispatch-loop", action="store_true",
12241 help="emit control flow the old way, as one loop around a switch (to compare with the default)") 12630 help="emit control flow the old way, as one loop around a switch (to compare with the default)")
12631 ap.add_argument("--no-float-controls", action="store_true",
12632 help="don't declare SignedZeroInfNanPreserve (for a driver whose "
12633 "shaderSignedZeroInfNanPreserveFloat32 is false); NaN, inf and -0 are then not guaranteed")
12242 ap.add_argument("--wave64-emulate", action="store_true", 12634 ap.add_argument("--wave64-emulate", action="store_true",
12243 help="wave64 compute and mesh shaders exact on any subgroup size (32-wide NVIDIA, Intel): " 12635 help="wave64 compute and mesh shaders exact on any subgroup size (32-wide NVIDIA, Intel): "
12244 "cross-lane operations go through workgroup memory instead of subgroup operations") 12636 "cross-lane operations go through workgroup memory instead of subgroup operations")
@@ -12276,6 +12668,8 @@ def main():
12276 global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, F16_HALVES 12668 global STRUCTURED, WAVE64_EMULATE, WAVE64_GRAPHICS, BARY_FALLBACK, TEXEL_OFFSET_FALLBACK, MESH_COMPUTE, FMA_KHR, F16_HALVES
12277 FMA_KHR = a.fma == "khr" 12669 FMA_KHR = a.fma == "khr"
12278 STRUCTURED = not a.dispatch_loop 12670 STRUCTURED = not a.dispatch_loop
12671 global FLOAT_CONTROLS
12672 FLOAT_CONTROLS = not a.no_float_controls
12279 WAVE64_EMULATE = a.wave64_emulate 12673 WAVE64_EMULATE = a.wave64_emulate
12280 WAVE64_GRAPHICS = a.wave64_graphics 12674 WAVE64_GRAPHICS = a.wave64_graphics
12281 BARY_FALLBACK = a.bary_fallback 12675 BARY_FALLBACK = a.bary_fallback
@@ -12334,9 +12728,11 @@ def main():
12334 ok += 1 12728 ok += 1
12335 sa = os.path.join(a.out, name + ".spvasm") 12729 sa = os.path.join(a.out, name + ".spvasm")
12336 sv = os.path.join(a.out, name + ".spv") 12730 sv = os.path.join(a.out, name + ".spv")
12337 with open(sa, "w", newline="\n") as f: 12731 write_asm = not (a.no_asm and a.assembler == "python")
12338 f.write(asm) 12732 if write_asm:
12339 r = assemble_spirv(sa, sv) 12733 with open(sa, "w", newline="\n") as f:
12734 f.write(asm)
12735 r = assemble_spirv(sa, sv, asm_text=asm, assembler=a.assembler)
12340 if r.returncode == 0: 12736 if r.returncode == 0:
12341 valid += 1 12737 valid += 1
12342 try: 12738 try:
@@ -12345,6 +12741,9 @@ def main():
12345 except Exception as e: # noqa: BLE001 - metadata must never cost a translation 12741 except Exception as e: # noqa: BLE001 - metadata must never cost a translation
12346 meta[name] = {"error": f"{type(e).__name__}: {e}"} 12742 meta[name] = {"error": f"{type(e).__name__}: {e}"}
12347 else: 12743 else:
12744 if not write_asm:
12745 with open(sa, "w", newline="\n") as f:
12746 f.write(asm)
12348 drop_stale(name) 12747 drop_stale(name)
12349 why["INVALID: " + (r.stderr.strip().splitlines() or ["?"])[0][:90]] += 1 12748 why["INVALID: " + (r.stderr.strip().splitlines() or ["?"])[0][:90]] += 1
12350 if a.no_asm and os.path.exists(sa): 12749 if a.no_asm and os.path.exists(sa):
diff --git a/tools/report_paths.py b/tools/report_paths.py
new file mode 100644
index 000000000..120b43fac
--- /dev/null
+++ b/tools/report_paths.py
@@ -0,0 +1,50 @@
1"""Do two report paths name the same file? One answer for the tools that refuse an output that would overwrite
2an input or another output.
3
4 from report_paths import same_report_path # after sys.path.insert(0, <this folder>), as -I needs
5
6`same_report_path(first, second)` is true when the two paths resolve to one name (`realpath`, then `normcase`, and on a
7case-insensitive macOS volume also case-folded and with composed and decomposed accents treated alike) or when both
8exist and `os.path.samefile` says they are one file (a hard link, another spelling the name rules missed). Neither
9path has to exist: two report paths that don't exist yet still collide when they differ only in case on a volume that
10ignores case. Standard library only; no game data.
11"""
12import os
13import sys
14import unicodedata
15
16_PC_CASE_SENSITIVE = 11 # <sys/unistd.h> on macOS; os.pathconf_names doesn't list it
17
18
19def case_insensitive_volume(path):
20 """True when the volume that will hold `path` ignores letter case, as macOS's default APFS volume does.
21 os.path.normcase folds case only on Windows, so on macOS `R.json` and `r.json` would pass as two reports."""
22 if sys.platform != "darwin":
23 return False
24 while not os.path.exists(path):
25 parent = os.path.dirname(path)
26 if parent == path:
27 break
28 path = parent
29 try:
30 return os.pathconf(path, _PC_CASE_SENSITIVE) == 0
31 except (OSError, ValueError):
32 return True # the macOS default; folding can only refuse a pair, never overwrite one
33
34
35def path_key(path):
36 """A name two spellings of one path share: realpath, normcase, and on a case-insensitive volume case-folded NFD."""
37 path = os.path.normcase(os.path.realpath(path))
38 if case_insensitive_volume(path):
39 # APFS and HFS+ also treat composed and decomposed accents as one name.
40 path = unicodedata.normalize("NFD", path.casefold())
41 return path
42
43
44def same_report_path(first, second):
45 if path_key(first) == path_key(second):
46 return True
47 try:
48 return os.path.samefile(first, second)
49 except OSError:
50 return False
diff --git a/tools/restofworld_index.py b/tools/restofworld_index.py
index 76b263ded..a776054cf 100644
--- a/tools/restofworld_index.py
+++ b/tools/restofworld_index.py
@@ -269,11 +269,28 @@ def scan_rpf(path, start=None, limit=None, max_inflate=MAX_INFLATE):
269 return rows, summary 269 return rows, summary
270 270
271 271
272def _carve_index(path):
273 """rpf9_carve.py's index.json in `path`: ({file name: stored bytes}, summary), or ({}, {}) without one."""
274 try:
275 with open(os.path.join(path, "index.json"), encoding="utf-8") as f:
276 index = json.load(f)
277 stored = {f"{int(e['off']):012x}.bin": int(e["stored"]) for e in index.get("files", [])}
278 summary = index.get("summary", {})
279 return stored, summary if isinstance(summary, dict) else {}
280 except (OSError, ValueError, TypeError, KeyError, AttributeError):
281 return {}, {}
282
283
272def scan_dir(path, max_inflate=MAX_INFLATE): 284def scan_dir(path, max_inflate=MAX_INFLATE):
273 """Index already-carved files. A leading hexadecimal file name supplies the offset.""" 285 """Index already-carved files. A leading hexadecimal file name supplies the offset.
286
287 With rpf9_carve.py's index.json in the folder, each file's stored (compressed) size and the carve's span,
288 zero padding and unread bytes come from it, so compressed_bytes and readable_fraction mean what they mean in
289 archive mode. Without it, a file's stored size can only be its length on disk (the inflated size)."""
274 rows = [] 290 rows = []
275 skipped = 0 291 skipped = 0
276 t0 = time.time() 292 t0 = time.time()
293 carve_stored, carve_summary = _carve_index(path)
277 for name in sorted(os.listdir(path)): 294 for name in sorted(os.listdir(path)):
278 full = os.path.join(path, name) 295 full = os.path.join(path, name)
279 if not os.path.isfile(full) or not (name.endswith(".bin") or name.endswith(".bk2")): 296 if not os.path.isfile(full) or not (name.endswith(".bin") or name.endswith(".bk2")):
@@ -285,13 +302,18 @@ def scan_dir(path, max_inflate=MAX_INFLATE):
285 offset = int(found.group(1), 16) if found else len(rows) 302 offset = int(found.group(1), 16) if found else len(rows)
286 with open(full, "rb") as f: 303 with open(full, "rb") as f:
287 data = f.read() 304 data = f.read()
305 stored = carve_stored.get(name, len(data))
288 if len(data) >= 3 and data[:3] == b"KB2": 306 if len(data) >= 3 and data[:3] == b"KB2":
289 row = classify(data, offset, len(data)) 307 row = classify(data, offset, stored)
290 else: 308 else:
291 row = classify(data, offset, len(data)) 309 row = classify(data, offset, stored)
292 row["size"] = len(data) 310 row["size"] = len(data)
293 rows.append(row) 311 rows.append(row)
294 summary = summarise(rows, sum(r["stored"] for r in rows), 0, 0) 312 if carve_stored and "span" in carve_summary:
313 summary = summarise(rows, int(carve_summary["span"]), int(carve_summary.get("zero_padding", 0)),
314 int(carve_summary.get("unread_bytes", 0)))
315 else:
316 summary = summarise(rows, sum(r["stored"] for r in rows), 0, 0)
295 summary.update(mode="directory", directory=path, elapsed_seconds=round(time.time() - t0, 3), 317 summary.update(mode="directory", directory=path, elapsed_seconds=round(time.time() - t0, 3),
296 skipped_candidates=skipped) 318 skipped_candidates=skipped)
297 return rows, summary 319 return rows, summary
diff --git a/tools/root_sig_contract.py b/tools/root_sig_contract.py
index 167b1fb22..944badcfc 100644
--- a/tools/root_sig_contract.py
+++ b/tools/root_sig_contract.py
@@ -46,8 +46,8 @@ def pack_layout(sig):
46 ptype = p.get("type", "") 46 ptype = p.get("type", "")
47 if ptype == "constants": 47 if ptype == "constants":
48 count = p.get("count", 0) 48 count = p.get("count", 0)
49 if not isinstance(count, int) or count < 1: 49 if type(count) is not int or count < 1:
50 return [], f"param {index}: constants need count >= 1" 50 return [], f"param {index}: constants need an integer count >= 1"
51 width, cost_add = count, count 51 width, cost_add = count, count
52 elif ptype in ("cbv", "srv", "uav"): 52 elif ptype in ("cbv", "srv", "uav"):
53 width, cost_add = 2, 2 53 width, cost_add = 2, 2
@@ -93,8 +93,8 @@ def reconcile(shader_reads, dwords):
93 issues.append( 93 issues.append(
94 f"s{sgpr} ({kind}) incompatible with param " 94 f"s{sgpr} ({kind}) incompatible with param "
95 f"{slot['param']} ({slot['ptype']})") 95 f"{slot['param']} ({slot['ptype']})")
96 elif kind == "ptr64_lo" and slot["sub"] != 0: 96 elif kind in ("ptr32_lo", "ptr64_lo") and slot["sub"] != 0:
97 issues.append(f"s{sgpr} (ptr64_lo) reads the high half of the address") 97 issues.append(f"s{sgpr} ({kind}) reads the high half of the address")
98 if kind == "ptr64_hi": 98 if kind == "ptr64_hi":
99 lo = dwords[sgpr - 1] if sgpr > 0 else None 99 lo = dwords[sgpr - 1] if sgpr > 0 else None
100 if slot["sub"] != 1 or lo is None or lo["param"] != slot["param"] \ 100 if slot["sub"] != 1 or lo is None or lo["param"] != slot["param"] \
diff --git a/tools/rpf9_carve.py b/tools/rpf9_carve.py
index 9621ea212..ccdce0c9d 100644
--- a/tools/rpf9_carve.py
+++ b/tools/rpf9_carve.py
@@ -4,11 +4,23 @@ The data area is mostly zlib streams laid end to end, separated by zero padding.
4every stream that decodes cleanly to the end, and writes each one as <offset>.bin. It also records which byte 4every stream that decodes cleanly to the end, and writes each one as <offset>.bin. It also records which byte
5ranges it couldn't read, so coverage is measurable. 5ranges it couldn't read, so coverage is measurable.
6 6
7index.json holds the summary (totals), `files` (one row per carved stream) and `unread`: one row per gap between
8streams (or after the last one) that is not all zero bytes, with its offset, size and the Shannon entropy in
9bits/byte of its first ENTROPY_SAMPLE bytes (`sampled`). An all-zero gap is padding and only counts toward
10`zero_padding`. The bytes are counted, never decoded.
11
7Usage: 12Usage:
8 python -I rpf9_carve.py <archive.rpf> <out_dir> [--start N] [--limit BYTES] [--index-only] 13 python -I rpf9_carve.py <archive.rpf> <out_dir> [--start N] [--limit BYTES] [--until-adat] [--index-only]
14
15--until-adat ends the scan at the first raw AWC bank (a little-endian `ADAT` whose header parses as one,
16rsc8_audio.parse_adat_header_bytes), so the zlib-compressed audio config at the start of audio.rpf is carved without
17touching the banks and without a build-specific --limit (docs/audio_config.md). The bytes `ADAT` alone are not
18enough: they also occur inside `METADATA` and in compressed data. index.json's summary records the boundary.
9""" 19"""
10import argparse 20import argparse
21import collections
11import json 22import json
23import math
12import mmap 24import mmap
13import os 25import os
14import re 26import re
@@ -17,10 +29,35 @@ import sys
17import time 29import time
18import zlib 30import zlib
19 31
32sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
33from rsc8_audio import parse_adat_header_bytes # noqa: E402
34
20# zlib stream start, or a Bink 2 video ('KB2' + revision letter, then u32 size-8). 35# zlib stream start, or a Bink 2 video ('KB2' + revision letter, then u32 size-8).
21# RPF9 magic as it sits on disk: the tag "RPF9" stored little-endian (docs/rpf.md, docs/bvh.md). 36# RPF9 magic as it sits on disk: the tag "RPF9" stored little-endian (docs/rpf.md, docs/bvh.md).
22MAGIC = b"9FPR" 37MAGIC = b"9FPR"
23ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") 38ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]")
39ENTROPY_SAMPLE = 1 << 20 # bytes of an unread range used for its entropy
40GAP_CHUNK = 1 << 20 # a gap is checked this many bytes at a time: one can be gigabytes long
41
42
43def all_zero(buf, a, b, chunk=GAP_CHUNK):
44 """Whether buf[a:b] is all zero bytes, reading at most `chunk` bytes at a time.
45
46 Slicing a whole gap of a multi-gigabyte archive at once ran out of memory (a 20 GB archive in this package).
47 """
48 for p in range(a, b, chunk):
49 piece = buf[p:min(p + chunk, b)]
50 if piece.count(0) != len(piece):
51 return False
52 return True
53
54
55def entropy(sample):
56 """Shannon entropy of a byte string in bits per byte (0.0 for an empty one)."""
57 if not sample:
58 return 0.0
59 n = len(sample)
60 return -sum(c / n * math.log2(c / n) for c in collections.Counter(sample).values())
24 61
25 62
26def below_normal(): 63def below_normal():
@@ -52,12 +89,32 @@ def byte_count(text):
52 return value 89 return value
53 90
54 91
92ADAT_HEADER_READ = 1 << 20 # enough for every bank header the parser accepts in practice; it rejects longer ones
93
94
95def first_adat_bank(m, start, end):
96 """Offset of the first raw AWC bank in m[start:end] whose header parses (not just the four bytes), or None."""
97 size = len(m)
98 pos = start
99 while pos < end:
100 at = m.find(b"ADAT", pos, end)
101 if at < 0:
102 return None
103 if parse_adat_header_bytes(m[at:min(size, at + ADAT_HEADER_READ)], at, size) is not None:
104 return at
105 pos = at + 1
106 return None
107
108
55def main() -> int: 109def main() -> int:
56 ap = argparse.ArgumentParser() 110 ap = argparse.ArgumentParser()
57 ap.add_argument("archive") 111 ap.add_argument("archive")
58 ap.add_argument("out") 112 ap.add_argument("out")
59 ap.add_argument("--start", type=offset) 113 ap.add_argument("--start", type=offset)
60 ap.add_argument("--limit", type=byte_count) 114 ap.add_argument("--limit", type=byte_count)
115 ap.add_argument("--until-adat", action="store_true",
116 help="end the scan at the first raw AWC (ADAT) bank, e.g. the audio config at the start of "
117 "audio.rpf")
61 ap.add_argument("--index-only", action="store_true") 118 ap.add_argument("--index-only", action="store_true")
62 a = ap.parse_args() 119 a = ap.parse_args()
63 below_normal() 120 below_normal()
@@ -86,7 +143,28 @@ def main() -> int:
86 m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) 143 m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
87 pos = base 144 pos = base
88 end = min(size, pos + a.limit) if a.limit else size 145 end = min(size, pos + a.limit) if a.limit else size
146 boundary = None
147 if a.until_adat:
148 boundary = first_adat_bank(m, pos, end)
149 if boundary is None:
150 print(f"--until-adat: no AWC bank between {pos:#x} and {end:#x}; scanning all of it", flush=True)
151 else:
152 end = boundary
153 print(f"--until-adat: first AWC bank at {boundary:#x}; scanning {pos:#x}..{boundary:#x}", flush=True)
89 rows, last, unread, zero = [], pos, 0, 0 154 rows, last, unread, zero = [], pos, 0, 0
155 unread_ranges = []
156
157 def account(a, b):
158 """Count the gap m[a:b] as zero padding, or as an unread range that is also listed."""
159 nonlocal zero, unread
160 if all_zero(m, a, b):
161 zero += b - a
162 return
163 unread += b - a
164 sample = m[a:min(b, a + ENTROPY_SAMPLE)]
165 unread_ranges.append({"off": a, "size": b - a, "entropy": round(entropy(sample), 3),
166 "sampled": len(sample)})
167
90 t0 = time.time() 168 t0 = time.time()
91 while pos < end: 169 while pos < end:
92 mt = ZHDR.search(m, pos, end) 170 mt = ZHDR.search(m, pos, end)
@@ -102,11 +180,7 @@ def main() -> int:
102 if not (64 <= blen <= end - s and 16 <= w <= 8192 and 16 <= h <= 8192): 180 if not (64 <= blen <= end - s and 16 <= w <= 8192 and 16 <= h <= 8192):
103 pos = s + 1 181 pos = s + 1
104 continue 182 continue
105 gap = m[last:s] 183 account(last, s)
106 if gap.count(0) == len(gap):
107 zero += len(gap)
108 else:
109 unread += len(gap)
110 rows.append({"off": s, "stored": blen, "size": blen, "type": "bink2", "w": w, "h": h, 184 rows.append({"off": s, "stored": blen, "size": blen, "type": "bink2", "w": w, "h": h,
111 "frames": struct.unpack_from("<I", m, s + 8)[0], "pre": "", "head": m[s:s + 16].hex()}) 185 "frames": struct.unpack_from("<I", m, s + 8)[0], "pre": "", "head": m[s:s + 16].hex()})
112 if not a.index_only: 186 if not a.index_only:
@@ -135,11 +209,7 @@ def main() -> int:
135 pos = s + 1 209 pos = s + 1
136 continue 210 continue
137 used = p - s - len(d.unused_data) 211 used = p - s - len(d.unused_data)
138 gap = m[last:s] 212 account(last, s)
139 if gap.count(0) == len(gap):
140 zero += len(gap)
141 else:
142 unread += len(gap)
143 rows.append({"off": s, "stored": used, "size": len(out), "pre": m[max(0, s - 16):s].hex(), 213 rows.append({"off": s, "stored": used, "size": len(out), "pre": m[max(0, s - 16):s].hex(),
144 "head": out[:16].hex()}) 214 "head": out[:16].hex()})
145 if not a.index_only: 215 if not a.index_only:
@@ -149,24 +219,25 @@ def main() -> int:
149 if len(rows) % 2000 == 0: 219 if len(rows) % 2000 == 0:
150 done = (pos - (a.start or 0)) / max(1, end - (a.start or 0)) 220 done = (pos - (a.start or 0)) / max(1, end - (a.start or 0))
151 print(f"[{done:6.1%}] {len(rows)} files, {time.time() - t0:.0f}s", flush=True) 221 print(f"[{done:6.1%}] {len(rows)} files, {time.time() - t0:.0f}s", flush=True)
152 tail = m[last:end] 222 account(last, end)
153 if tail.count(0) == len(tail):
154 zero += len(tail)
155 else:
156 unread += len(tail)
157 total = sum(r["stored"] for r in rows) 223 total = sum(r["stored"] for r in rows)
158 bink = sum(r["stored"] for r in rows if r.get("type") == "bink2") 224 bink = sum(r["stored"] for r in rows if r.get("type") == "bink2")
159 span = end - base 225 span = end - base
160 summary = {"archive": a.archive, "files": len(rows), "compressed_bytes": total, 226 summary = {"archive": a.archive, "files": len(rows), "compressed_bytes": total,
161 "inflated_bytes": sum(r["size"] for r in rows), "bink2_bytes": bink, 227 "inflated_bytes": sum(r["size"] for r in rows), "bink2_bytes": bink,
162 "bink2_files": sum(1 for r in rows if r.get("type") == "bink2"), 228 "bink2_files": sum(1 for r in rows if r.get("type") == "bink2"),
163 "zero_padding": zero, "unread_bytes": unread, 229 "zero_padding": zero, "unread_bytes": unread, "unread_ranges": len(unread_ranges),
164 "span": span} 230 "span": span}
231 if a.until_adat:
232 summary["first_adat_bank"] = boundary # None: no bank in the window, the whole window was scanned
165 with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8", newline="\n") as f: 233 with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8", newline="\n") as f:
166 json.dump({"summary": summary, "files": rows}, f) 234 json.dump({"summary": summary, "files": rows, "unread": unread_ranges}, f)
167 print(json.dumps(summary, indent=1)) 235 print(json.dumps(summary, indent=1))
168 span = max(1, span) # an empty data area (or --start at the end) has nothing to divide by 236 span = max(1, span) # an empty data area (or --start at the end) has nothing to divide by
169 print(f"readable: {total / span:.1%}, zero padding {zero / span:.1%}, unread {unread / span:.1%}") 237 print(f"readable: {total / span:.1%}, zero padding {zero / span:.1%}, unread {unread / span:.1%}")
238 if unread_ranges:
239 print(f"unread: {len(unread_ranges)} range(s), largest {max(r['size'] for r in unread_ranges)} bytes "
240 f"(listed in index.json)")
170 return 0 241 return 0
171 242
172 243
diff --git a/tools/rpf9dump/rpf9dump.csproj b/tools/rpf9dump/rpf9dump.csproj
index 7b6bbfed4..e14313b6f 100644
--- a/tools/rpf9dump/rpf9dump.csproj
+++ b/tools/rpf9dump/rpf9dump.csproj
@@ -1,5 +1,5 @@
1<Project Sdk="Microsoft.NET.Sdk"> 1<Project Sdk="Microsoft.NET.Sdk">
2 <PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><ServerGarbageCollection>true</ServerGarbageCollection><RestorePackagesWithLockFile>true</RestorePackagesWithLockFile></PropertyGroup> 2 <PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><RollForward>Major</RollForward><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><ServerGarbageCollection>true</ServerGarbageCollection><RestorePackagesWithLockFile>true</RestorePackagesWithLockFile></PropertyGroup>
3 <!-- third_party/rpf9-explorer is a git submodule (git submodule update, with the init option) --> 3 <!-- third_party/rpf9-explorer is a git submodule (git submodule update, with the init option) -->
4 <ItemGroup><ProjectReference Include="..\..\third_party\rpf9-explorer\Core\RpfPreview.Core.csproj" /></ItemGroup> 4 <ItemGroup><ProjectReference Include="..\..\third_party\rpf9-explorer\Core\RpfPreview.Core.csproj" /></ItemGroup>
5</Project> 5</Project>
diff --git a/tools/rpf_probe.py b/tools/rpf_probe.py
index 49b512b3d..13cdf248d 100644
--- a/tools/rpf_probe.py
+++ b/tools/rpf_probe.py
@@ -16,6 +16,10 @@ import sys
16import tempfile 16import tempfile
17from collections import Counter 17from collections import Counter
18 18
19# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module.
20sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
21from report_paths import same_report_path # noqa: E402
22
19 23
20def entropy(b: bytes) -> float: 24def entropy(b: bytes) -> float:
21 if not b: 25 if not b:
@@ -42,15 +46,6 @@ def probe(path: str) -> dict:
42 } 46 }
43 47
44 48
45def _same_report_path(first: str, second: str) -> bool:
46 if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)):
47 return True
48 try:
49 return os.path.samefile(first, second)
50 except OSError:
51 return False
52
53
54def main() -> int: 49def main() -> int:
55 ap = argparse.ArgumentParser() 50 ap = argparse.ArgumentParser()
56 ap.add_argument("game_dir") 51 ap.add_argument("game_dir")
@@ -68,7 +63,7 @@ def main() -> int:
68 if name.lower().endswith(".rpf"): 63 if name.lower().endswith(".rpf"):
69 archives.append(os.path.join(root, name)) 64 archives.append(os.path.join(root, name))
70 for path in archives: 65 for path in archives:
71 if _same_report_path(a.out, path): 66 if same_report_path(a.out, path):
72 print(f"ERROR: --out would overwrite an input archive: {path}", file=sys.stderr) 67 print(f"ERROR: --out would overwrite an input archive: {path}", file=sys.stderr)
73 return 2 68 return 2
74 for path in archives: 69 for path in archives:
diff --git a/tools/rtti_scan.py b/tools/rtti_scan.py
index ca769ed08..710cabc7f 100644
--- a/tools/rtti_scan.py
+++ b/tools/rtti_scan.py
@@ -199,8 +199,8 @@ def write_report(path, text):
199 parent = os.path.dirname(os.path.abspath(path)) 199 parent = os.path.dirname(os.path.abspath(path))
200 tmp = None 200 tmp = None
201 try: 201 try:
202 with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=parent, prefix=".rtti-", suffix=".tmp", 202 with tempfile.NamedTemporaryFile("w", encoding="utf-8", newline="\n", dir=parent, prefix=".rtti-",
203 delete=False) as f: 203 suffix=".tmp", delete=False) as f:
204 tmp = f.name 204 tmp = f.name
205 f.write(text) 205 f.write(text)
206 os.chmod(tmp, published_mode(path)) 206 os.chmod(tmp, published_mode(path))
diff --git a/tools/salu_diff.py b/tools/salu_diff.py
index 9108d5e01..38d8bde03 100644
--- a/tools/salu_diff.py
+++ b/tools/salu_diff.py
@@ -89,11 +89,25 @@ def s64(x):
89 return x - (1 << 64) if x >> 63 else x 89 return x - (1 << 64) if x >> 63 else x
90 90
91 91
92def sext8(x):
93 x &= 0xFF
94 return x - 0x100 if x & 0x80 else x
95
96
92def sext16(x): 97def sext16(x):
93 x &= 0xFFFF 98 x &= 0xFFFF
94 return x - 0x10000 if x & 0x8000 else x 99 return x - 0x10000 if x & 0x8000 else x
95 100
96 101
102def flbit32(x):
103 x &= M32
104 sign = x >> 31
105 for n in range(1, 32):
106 if (x >> (31 - n)) & 1 != sign:
107 return n
108 return M32
109
110
97def is_nan(w): 111def is_nan(w):
98 return (w & 0x7F800000) == 0x7F800000 and (w & 0x7FFFFF) != 0 112 return (w & 0x7F800000) == 0x7F800000 and (w & 0x7FFFFF) != 0
99 113
@@ -122,7 +136,7 @@ def bfe(src, ctl, signed):
122 off, width = ctl & 31, (ctl >> 16) & 0x7F 136 off, width = ctl & 31, (ctl >> 16) & 0x7F
123 # A field that runs past bit 31 stops there: s_bfe_i32 sign-extends from the top bit that exists (LLVM 137 # A field that runs past bit 31 stops there: s_bfe_i32 sign-extends from the top bit that exists (LLVM
124 # constantFoldBFE does for v_bfe; 5-bit width there). The s_bfe rule itself rests on the gfx1150 measurement 138 # constantFoldBFE does for v_bfe; 5-bit width there). The s_bfe rule itself rests on the gfx1150 measurement
125 # (4000 random control words, --oracle hw), and RDNA2 agrees: gfx1036, 20,000 programs with --bfe-any. 139 # (4000 random control words, --oracle hw), and RDNA2 agrees: gfx1036 (counts in the s_bfe row of docs/design.md).
126 width = min(width, 32 - off) 140 width = min(width, 32 - off)
127 if width == 0: 141 if width == 0:
128 return 0 142 return 0
@@ -165,8 +179,17 @@ def _sop2():
165 add("s_bfm_b32", lambda a, b, c: ((((1 << (a & 31)) - 1) << (b & 31)) & M32, None)) 179 add("s_bfm_b32", lambda a, b, c: ((((1 << (a & 31)) - 1) << (b & 31)) & M32, None))
166 add("s_mul_i32", lambda a, b, c: ((s32(a) * s32(b)) & M32, None)) 180 add("s_mul_i32", lambda a, b, c: ((s32(a) * s32(b)) & M32, None))
167 add("s_mul_hi_u32", lambda a, b, c: ((a * b) >> 32, None)) 181 add("s_mul_hi_u32", lambda a, b, c: ((a * b) >> 32, None))
182 add("s_mul_hi_i32", lambda a, b, c: (((s32(a) * s32(b)) >> 32) & M32, None))
183 add("s_absdiff_i32", lambda a, b, c: (abs(s32((a - b) & M32)) & M32, int(abs(s32((a - b) & M32)) & M32 != 0)))
184 add("s_lshl1_add_u32", lambda a, b, c: (((a << 1) + b) & M32, int(((a << 1) + b) >= (1 << 32))))
185 add("s_lshl2_add_u32", lambda a, b, c: (((a << 2) + b) & M32, int(((a << 2) + b) >= (1 << 32))))
186 add("s_lshl3_add_u32", lambda a, b, c: (((a << 3) + b) & M32, int(((a << 3) + b) >= (1 << 32))))
187 add("s_lshl4_add_u32", lambda a, b, c: (((a << 4) + b) & M32, int(((a << 4) + b) >= (1 << 32))))
168 add("s_bfe_u32", lambda a, b, c: (bfe(a, b, False), int(bfe(a, b, False) != 0))) 188 add("s_bfe_u32", lambda a, b, c: (bfe(a, b, False), int(bfe(a, b, False) != 0)))
169 add("s_bfe_i32", lambda a, b, c: (bfe(a, b, True), int(bfe(a, b, True) != 0))) 189 add("s_bfe_i32", lambda a, b, c: (bfe(a, b, True), int(bfe(a, b, True) != 0)))
190 add("s_pack_ll_b32_b16", lambda a, b, c: (((b & 0xFFFF) << 16) | (a & 0xFFFF), None))
191 add("s_pack_lh_b32_b16", lambda a, b, c: ((b & 0xFFFF0000) | (a & 0xFFFF), None))
192 add("s_pack_hh_b32_b16", lambda a, b, c: ((b & 0xFFFF0000) | ((a >> 16) & 0xFFFF), None))
170 return ops 193 return ops
171 194
172 195
@@ -195,6 +218,9 @@ def _sop1():
195 "s_ff0_i32_b32": ("sop1", lambda a, b, c: (first_set(~a & M32, 32), None)), 218 "s_ff0_i32_b32": ("sop1", lambda a, b, c: (first_set(~a & M32, 32), None)),
196 "s_ff1_i32_b32": ("sop1", lambda a, b, c: (first_set(a, 32), None)), 219 "s_ff1_i32_b32": ("sop1", lambda a, b, c: (first_set(a, 32), None)),
197 "s_flbit_i32_b32": ("sop1", lambda a, b, c: (32 - a.bit_length() if a else M32, None)), 220 "s_flbit_i32_b32": ("sop1", lambda a, b, c: (32 - a.bit_length() if a else M32, None)),
221 "s_flbit_i32": ("sop1", lambda a, b, c: (flbit32(a), None)),
222 "s_sext_i32_i8": ("sop1", lambda a, b, c: (sext8(a) & M32, None)),
223 "s_sext_i32_i16": ("sop1", lambda a, b, c: (sext16(a) & M32, None)),
198 "s_abs_i32": ("sop1", lambda a, b, c: (abs(s32(a)) & M32, int(abs(s32(a)) & M32 != 0))), 224 "s_abs_i32": ("sop1", lambda a, b, c: (abs(s32(a)) & M32, int(abs(s32(a)) & M32 != 0))),
199 "s_wqm_b32": ("sop1", lambda a, b, c: (wqm(a, 32), int(wqm(a, 32) != 0))), 225 "s_wqm_b32": ("sop1", lambda a, b, c: (wqm(a, 32), int(wqm(a, 32) != 0))),
200 # D is read: bit S0[4:0] of the destination is cleared or set. 226 # D is read: bit S0[4:0] of the destination is cleared or set.
diff --git a/tools/save_keys.py b/tools/save_keys.py
index 503b42bad..5605d0e2e 100644
--- a/tools/save_keys.py
+++ b/tools/save_keys.py
@@ -339,7 +339,14 @@ def main(argv=None):
339 a = ap.parse_args(argv) 339 a = ap.parse_args(argv)
340 if a.cmd == "resolve" and a.compose < 0: 340 if a.cmd == "resolve" and a.compose < 0:
341 r.error("--compose must be 0 or more") 341 r.error("--compose must be 0 or more")
342 return {"collect": cmd_collect, "resolve": cmd_resolve}[a.cmd](a) or 0 342 try:
343 return {"collect": cmd_collect, "resolve": cmd_resolve}[a.cmd](a) or 0
344 except OSError as e:
345 if e.filename is None: # not a file we were asked to read (a closed pipe, say)
346 raise
347 # A missing or unreadable input or --dict file is one line naming it, not a traceback.
348 print(f"error: {e.filename}: {e.strerror or e}", file=sys.stderr)
349 return 1
343 350
344 351
345if __name__ == "__main__": 352if __name__ == "__main__":
diff --git a/tools/sdwa_diff.py b/tools/sdwa_diff.py
new file mode 100644
index 000000000..15348aa86
--- /dev/null
+++ b/tools/sdwa_diff.py
@@ -0,0 +1,779 @@
1r"""Differential fuzzing of SDWA (sub-dword addressing) VALU forms. Standard library only.
2
3Generates seeded straight-line programs of `_sdwa` VOP1/VOP2/VOPC instructions, one lane, runs them through
4
5 * the reference below, written from the RDNA2 ISA guide's SDWA description and each opcode's pseudocode, and
6 * tools/rdna2spirv.py, executing the SPIR-V with tests/semantic/spirv_mini_interp.py,
7
8and compares four exported words bit for bit: three VGPRs and VCC (through v_cndmask_b32_e64). The reference does
9not share code with the translator or with tools/cpu_ref.py.
10
11What is modelled, per instruction:
12 * sources: VGPRs v1..v7, SGPRs s4..s7 (seeded with s_mov_b32, so the translator knows them as constants), integer
13 inline constants -16..64 and float inline constants (0.5, 1.0, 2.0, 4.0 and their negatives). A float constant
14 in an f16 op (v_cmp_class_f16's mask included) is the f16 value over a zero high half, in any other op
15 (v_cvt_f16_{u16,i16} included) its f32 bits. A source is narrowed to src0_sel/src1_sel (BYTE_0..3, WORD_0/1,
16 DWORD), constants too, zero-extended, or sign-extended under sext() (integer ops); then neg/abs (f16 ops, on
17 the sign bit of the f16 word) and the op.
18 * dst_sel and dst_unused: the result's low bits go to the selected field; UNUSED_PAD zeroes the other bits,
19 UNUSED_SEXT fills the bits above the field with its top bit (bits below stay zero), UNUSED_PRESERVE keeps them.
20 A 16-bit result (f16 ops, v_cvt_{u16,i16}_f16, v_cvt_f16_{u16,i16}) with dst_sel:DWORD zeroes the high half,
21 whatever dst_unused says: unlike the non-SDWA forms (docs/design.md "16-bit results"), which keep it.
22 * clamp: unsigned saturation on v_add/sub/subrev_nc_u32, [0, 1] on f16 results (clamp(-0) = +0) and on
23 v_cvt_f32_f16.
24 * f16 arithmetic rounds to nearest even with denormals kept (the MODE the translator assumes); min/max order -0
25 below +0; v_fract_f16(-0) = +0 and the result stops at 0x3bff.
26 * VOPC writes VCC (one bit, this lane); v_cndmask_b32 reads it.
27Every one of these rules was checked against an RDNA2 GPU (AMD Radeon iGPU, gfx1036, Windows driver 26.10.1) with
28--oracle hw, the f16 constant, dst_sel:DWORD and v_fract_f16(-0) rules included.
29
30The int family is the 32-bit integer VOP2 ops, v_cndmask_b32, the integer VOP1 ops and v_cvt_f32_{u32,i32,ubyteN},
31and the 32- and 16-bit integer compares. The f16 family is v_add/sub/subrev/mul/min/max_f16, the f16 rounding ops
32and v_fract_f16, the f16 <-> 16-bit integer and f16 -> f32 conversions, the f16 compares and v_cmp_class_f16.
33--list-ops prints them. Not generated: omod, v_cmpx, an SGPR destination for VOPC, DPP, literals (SDWA has none),
34transcendentals, f32 arithmetic.
35
36Skips (counted with their reasons): an f16 NaN operand of an op whose NaN result or IEEE-mode NaN rule is not
37modelled (the compares and v_cmp_class_f16 take NaNs), v_fract_f16 of an infinity, and anything the translator or
38the interpreter does not take: on main that is v_cmp_class_f16 (no f16 class compare in any encoding) and clamp
39on v_cvt_f16_{u16,i16}.
40
41Known divergences (KNOWN_DIVERGENCES): by default the generator leaves out the forms where the translator is known to
42differ from the hardware, so that a run shows new problems only; --known puts them back (a hardware-only run always
43has them):
44 * a constant shift amount (inline constant or seeded SGPR) for v_lshlrev_b32 / v_lshrrev_b32 / v_ashrrev_i32 with
45 src0_sel other than DWORD or sext(): the translator's constant fold shifted by the whole constant (#2005);
46 * a 16-bit result with dst_sel:DWORD: the translator keeps the destination's high half (finding in #1902);
47 * a float inline constant with a src_sel other than DWORD in an f16 op: the translator reads the whole constant
48 (finding in #1902).
49
50With --oracle hw the same programs also run natively on an AMD GPU (tools/hw_oracle/) and the hardware's four words
51are compared with the reference: that validates the reference itself. SDWA exists on GFX9 and GFX10 only, so the
52hardware oracle needs an RDNA1/RDNA2 GPU; anything else exits 77, like a missing tool. The kernel runs on one lane
53of a wave32 compute dispatch, so IEEE mode is on there (it only changes NaN rules, which are skipped).
54
55Usage:
56 python -I tools/sdwa_diff.py [--programs N] [--seed S] [--max-ops N] [--ops v_add_f16,v_cmp_lt_u16]
57 python -I tools/sdwa_diff.py --family f16 # int, f16 or all (default)
58 python -I tools/sdwa_diff.py --known # also the forms in KNOWN_DIVERGENCES
59 python -I tools/sdwa_diff.py --oracle hw # hardware vs reference only
60 python -I tools/sdwa_diff.py --oracle translator,hw
61 python -I tools/sdwa_diff.py --list-ops
62 python -I tools/sdwa_diff.py --self-test
63
64Exit 0 when every program matches, 1 on a mismatch (the shortest failing program is printed after removing
65instructions that do not matter), 2 on a harness error, 77 when the requested hardware oracle is unavailable.
66"""
67import argparse
68import gc
69import math
70import os
71import random
72import re
73import struct
74import sys
75import tempfile
76import warnings
77
78HERE = os.path.dirname(os.path.abspath(__file__))
79sys.dont_write_bytecode = True
80if HERE not in sys.path:
81 sys.path.insert(0, HERE)
82SEM_DIR = os.path.join(os.path.dirname(HERE), "tests", "semantic")
83if SEM_DIR not in sys.path:
84 sys.path.insert(0, SEM_DIR)
85
86M32 = 0xFFFFFFFF
87STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4)
88
89VREGS = tuple(range(1, 8)) # data VGPRs v1..v7 (v0 is the hardware kernel's store offset)
90SREGS = (4, 5, 6, 7) # data SGPRs s4..s7
91N_SEED = len(VREGS) + len(SREGS) + 1 # the seed lines: VGPRs, SGPRs, VCC
92N_OBS = 4 # the observation lines: v8..v10 copies, v11 = VCC
93
94SEL = {"BYTE_0": (0, 8), "BYTE_1": (8, 8), "BYTE_2": (16, 8), "BYTE_3": (24, 8),
95 "WORD_0": (0, 16), "WORD_1": (16, 16), "DWORD": (0, 32)}
96UNUSED = ("UNUSED_PAD", "UNUSED_SEXT", "UNUSED_PRESERVE")
97FLOAT_CONSTS = {"0.5": 0x3F000000, "-0.5": 0xBF000000, "1.0": 0x3F800000, "-1.0": 0xBF800000,
98 "2.0": 0x40000000, "-2.0": 0xC0000000, "4.0": 0x40800000, "-4.0": 0xC0800000}
99FLOAT_CONSTS_F16 = {"0.5": 0x3800, "-0.5": 0xB800, "1.0": 0x3C00, "-1.0": 0xBC00,
100 "2.0": 0x4000, "-2.0": 0xC000, "4.0": 0x4400, "-4.0": 0xC400}
101
102INTERESTING = (0, 1, 2, 0x7F, 0x80, 0xFF, 0x7FFF, 0x8000, 0xFFFF, 0x10000, 0x7FFFFFFF, 0x80000000, M32,
103 0x00FF00FF, 0x80808080, 0x8000FFFF, 0x12345678, 0xDEADBEEF, 31, 32, 33)
104F16_INTERESTING = (0x0000, 0x8000, 0x3C00, 0xBC00, 0x3800, 0x3E00, 0xC100, 0x4200, 0x4400, 0x5640, 0xB400,
105 0x7BFF, 0xFBFF, 0x7C00, 0xFC00, 0x0001, 0x83FF, 0x0400, 0x3BFF, 0x3C01, 0xC500, 0x4900)
106
107
108class Skip(Exception):
109 pass
110
111
112class RefError(Exception):
113 pass
114
115
116def s32(x):
117 x &= M32
118 return x - (1 << 32) if x >> 31 else x
119
120
121def sx(x, w):
122 x &= (1 << w) - 1
123 return x - (1 << w) if x >> (w - 1) else x
124
125
126# ---- f16 helpers (bit patterns in, bit patterns out) ------------------------------------------------------
127
128def h2f(h):
129 return struct.unpack("<e", struct.pack("<H", h & 0xFFFF))[0]
130
131
132def f2h(x):
133 """Round a Python float (exact here: every f16 sum or product fits a double) to f16, nearest even."""
134 if math.isnan(x):
135 raise Skip("reference: f16 NaN result (payload not modelled)")
136 try:
137 return struct.unpack("<H", struct.pack("<e", x))[0]
138 except OverflowError:
139 return 0x7C00 if x > 0 else 0xFC00
140
141
142def f2u(x):
143 return struct.unpack("<I", struct.pack("<f", x))[0]
144
145
146def is_nan16(h):
147 return (h & 0x7C00) == 0x7C00 and (h & 0x3FF) != 0
148
149
150def _no_nan(*hs):
151 if any(is_nan16(h) for h in hs):
152 raise Skip("reference: f16 NaN operand (IEEE-mode NaN rules not modelled)")
153
154
155def f16_bin(fn):
156 def op(a, b):
157 a, b = a & 0xFFFF, b & 0xFFFF
158 _no_nan(a, b)
159 return f2h(fn(h2f(a), h2f(b)))
160 return op
161
162
163def f16_minmax(want_max):
164 def op(a, b):
165 a, b = a & 0xFFFF, b & 0xFFFF
166 _no_nan(a, b)
167 # -0 orders below +0; otherwise the numeric order
168 ka, kb = (h2f(a), a >> 15 == 0), (h2f(b), b >> 15 == 0)
169 if want_max:
170 return a if ka > kb else b
171 return a if ka < kb else b
172 return op
173
174
175def f16_round(fn):
176 def op(a, b=0):
177 a &= 0xFFFF
178 _no_nan(a)
179 x = h2f(a)
180 if math.isinf(x):
181 return a
182 return f2h(math.copysign(float(fn(x)), x))
183 return op
184
185
186def f16_fract(a, b=0):
187 a &= 0xFFFF
188 _no_nan(a)
189 x = h2f(a)
190 if math.isinf(x):
191 raise Skip("reference: v_fract_f16 of an infinity (NaN result)")
192 # x + -floor(x): fract(-0) = -0 + +0 = +0 (gfx1036); the result stops at the largest f16 below 1.0
193 fl = math.copysign(float(math.floor(x)), x) if math.floor(x) == 0 else float(math.floor(x)) # floor(-0) = -0
194 return min(f2h(x + -fl), 0x3BFF)
195
196
197def cvt_u16_f16(a, b=0):
198 a &= 0xFFFF
199 _no_nan(a)
200 x = h2f(a)
201 return 0 if x <= 0 else 0xFFFF if x >= 65535 else int(x)
202
203
204def cvt_i16_f16(a, b=0):
205 a &= 0xFFFF
206 _no_nan(a)
207 x = h2f(a)
208 if x >= 32767:
209 return 0x7FFF
210 if x <= -32768:
211 return 0x8000
212 return int(x) & 0xFFFF
213
214
215def cmp_class_f16(a, b):
216 a &= 0xFFFF
217 e, m, neg = (a >> 10) & 0x1F, a & 0x3FF, a >> 15
218 if e == 0x1F:
219 bit = (0 if not m >> 9 else 1) if m else (2 if neg else 9)
220 elif e == 0:
221 bit = (4 if neg else 7) if m else (5 if neg else 6)
222 else:
223 bit = 3 if neg else 8
224 return (b >> bit) & 1
225
226
227def ffbh_i32(a):
228 a &= M32
229 if a in (0, M32):
230 return M32
231 x = a ^ M32 if a >> 31 else a
232 return 32 - x.bit_length()
233
234
235# ---- the reference: one entry per opcode -------------------------------------------------------------
236# (family, form, width, fn). family "int" / "f16" decides the modifiers (sext vs neg/abs) and how a float inline
237# constant reads. form: "vop2" d, a, b; "vop1" d, a; "vopc" vcc, a, b; "cndmask" d, a, b, vcc.
238# width: bits of the result (16 or 32); a 16-bit result has a zero high half under dst_sel:DWORD.
239# fn(a, b) gets the selected 32-bit sources and returns the result (a bit for "vopc").
240
241def _ops():
242 ops = {}
243
244 def add(name, family, form, fn, width=32, clamp=None):
245 ops[name] = (family, form, width, fn, clamp)
246
247 usat = "usat"
248 add("v_add_nc_u32", "int", "vop2", lambda a, b: a + b, clamp=usat)
249 add("v_sub_nc_u32", "int", "vop2", lambda a, b: a - b, clamp=usat)
250 add("v_subrev_nc_u32", "int", "vop2", lambda a, b: b - a, clamp=usat)
251 add("v_and_b32", "int", "vop2", lambda a, b: a & b)
252 add("v_or_b32", "int", "vop2", lambda a, b: a | b)
253 add("v_xor_b32", "int", "vop2", lambda a, b: a ^ b)
254 add("v_xnor_b32", "int", "vop2", lambda a, b: ~(a ^ b))
255 add("v_lshlrev_b32", "int", "vop2", lambda a, b: b << (a & 31))
256 add("v_lshrrev_b32", "int", "vop2", lambda a, b: (b & M32) >> (a & 31))
257 add("v_ashrrev_i32", "int", "vop2", lambda a, b: s32(b) >> (a & 31))
258 add("v_mul_u32_u24", "int", "vop2", lambda a, b: (a & 0xFFFFFF) * (b & 0xFFFFFF))
259 add("v_mul_hi_u32_u24", "int", "vop2", lambda a, b: ((a & 0xFFFFFF) * (b & 0xFFFFFF)) >> 32)
260 add("v_mul_i32_i24", "int", "vop2", lambda a, b: sx(a, 24) * sx(b, 24))
261 add("v_mul_hi_i32_i24", "int", "vop2", lambda a, b: (sx(a, 24) * sx(b, 24)) >> 32)
262 add("v_min_u32", "int", "vop2", lambda a, b: min(a & M32, b & M32))
263 add("v_max_u32", "int", "vop2", lambda a, b: max(a & M32, b & M32))
264 add("v_min_i32", "int", "vop2", lambda a, b: min(s32(a), s32(b)))
265 add("v_max_i32", "int", "vop2", lambda a, b: max(s32(a), s32(b)))
266 add("v_cndmask_b32", "int", "cndmask", None)
267 add("v_mov_b32", "int", "vop1", lambda a, b: a)
268 add("v_not_b32", "int", "vop1", lambda a, b: ~a)
269 add("v_bfrev_b32", "int", "vop1", lambda a, b: int(f"{a & M32:032b}"[::-1], 2))
270 add("v_ffbh_u32", "int", "vop1", lambda a, b: M32 if not a & M32 else 32 - (a & M32).bit_length())
271 add("v_ffbl_b32", "int", "vop1", lambda a, b: M32 if not a & M32 else ((a & -a) & M32).bit_length() - 1)
272 add("v_ffbh_i32", "int", "vop1", lambda a, b: ffbh_i32(a))
273 add("v_cvt_f32_u32", "int", "vop1", lambda a, b: f2u(float(a & M32)))
274 add("v_cvt_f32_i32", "int", "vop1", lambda a, b: f2u(float(s32(a))))
275 for n in range(4):
276 add(f"v_cvt_f32_ubyte{n}", "int", "vop1", lambda a, b, n=n: f2u(float((a >> (8 * n)) & 0xFF)))
277 cmps = {"f": lambda a, b: False, "lt": lambda a, b: a < b, "eq": lambda a, b: a == b,
278 "le": lambda a, b: a <= b, "gt": lambda a, b: a > b, "ne": lambda a, b: a != b,
279 "ge": lambda a, b: a >= b, "t": lambda a, b: True}
280 for c, f in cmps.items():
281 add(f"v_cmp_{c}_u32", "int", "vopc", lambda a, b, f=f: f(a & M32, b & M32))
282 add(f"v_cmp_{c}_i32", "int", "vopc", lambda a, b, f=f: f(s32(a), s32(b)))
283 if c not in ("f", "t"): # GFX10 has no v_cmp_f/t_{i16,u16}
284 add(f"v_cmp_{c}_u16", "int", "vopc", lambda a, b, f=f: f(a & 0xFFFF, b & 0xFFFF))
285 add(f"v_cmp_{c}_i16", "int", "vopc", lambda a, b, f=f: f(sx(a, 16), sx(b, 16)))
286
287 fclamp = "f16"
288 add("v_add_f16", "f16", "vop2", f16_bin(lambda x, y: x + y), 16, fclamp)
289 add("v_sub_f16", "f16", "vop2", f16_bin(lambda x, y: x - y), 16, fclamp)
290 add("v_subrev_f16", "f16", "vop2", f16_bin(lambda x, y: y - x), 16, fclamp)
291 add("v_mul_f16", "f16", "vop2", f16_bin(lambda x, y: x * y), 16, fclamp)
292 add("v_max_f16", "f16", "vop2", f16_minmax(True), 16, fclamp)
293 add("v_min_f16", "f16", "vop2", f16_minmax(False), 16, fclamp)
294 add("v_floor_f16", "f16", "vop1", f16_round(math.floor), 16, fclamp)
295 add("v_ceil_f16", "f16", "vop1", f16_round(math.ceil), 16, fclamp)
296 add("v_trunc_f16", "f16", "vop1", f16_round(math.trunc), 16, fclamp)
297 add("v_rndne_f16", "f16", "vop1", f16_round(round), 16, fclamp)
298 add("v_fract_f16", "f16", "vop1", f16_fract, 16, fclamp)
299 add("v_cvt_f32_f16", "f16", "vop1", lambda a, b: f2u(h2f(a)) if not is_nan16(a) else _no_nan(a), 32, "f32")
300 add("v_cvt_u16_f16", "f16", "vop1", cvt_u16_f16, 16)
301 add("v_cvt_i16_f16", "f16", "vop1", cvt_i16_f16, 16)
302 add("v_cvt_f16_u16", "int16", "vop1", lambda a, b: f2h(float(a & 0xFFFF)), 16, fclamp)
303 add("v_cvt_f16_i16", "int16", "vop1", lambda a, b: f2h(float(sx(a, 16))), 16, fclamp)
304
305 def fcmp(pred):
306 def op(a, b):
307 a, b = a & 0xFFFF, b & 0xFFFF
308 x, y = h2f(a), h2f(b)
309 unordered = math.isnan(x) or math.isnan(y)
310 return pred(x, y, unordered)
311 return op
312 fcmps = {"f": lambda x, y, u: False, "lt": lambda x, y, u: x < y, "eq": lambda x, y, u: x == y,
313 "le": lambda x, y, u: x <= y, "gt": lambda x, y, u: x > y, "lg": lambda x, y, u: not u and x != y,
314 "ge": lambda x, y, u: x >= y, "o": lambda x, y, u: not u, "u": lambda x, y, u: u,
315 "nge": lambda x, y, u: not x >= y, "nlg": lambda x, y, u: u or x == y, "ngt": lambda x, y, u: not x > y,
316 "nle": lambda x, y, u: not x <= y, "neq": lambda x, y, u: not x == y, "nlt": lambda x, y, u: not x < y,
317 "tru": lambda x, y, u: True}
318 for c, p in fcmps.items():
319 add(f"v_cmp_{c}_f16", "f16", "vopc", fcmp(p))
320 add("v_cmp_class_f16", "f16", "vopc", lambda a, b: cmp_class_f16(a, b & 0x3FF))
321 return ops
322
323
324OPS = _ops()
325CLAMP_OPS = tuple(sorted(o for o, v in OPS.items() if v[4]))
326
327
328# ---- program text: parsing ----------------------------------------------------------------------------
329
330_SRC = re.compile(r"^(?P<neg>-)?(?P<abs>\|)?(?:sext\((?P<sx>[^)]+)\)|(?P<tok>[^|]+))\|?$")
331
332
333def parse_src(tok):
334 """{'tok': register or constant text, 'neg', 'abs', 'sext'}."""
335 tok = tok.strip()
336 if tok in FLOAT_CONSTS or re.fullmatch(r"-?\d+", tok):
337 return {"tok": tok, "neg": False, "abs": False, "sext": False} # -16 is a constant, not neg(16)
338 m = _SRC.match(tok)
339 if not m:
340 raise RefError(f"source {tok!r}")
341 t = m.group("sx") or m.group("tok")
342 return {"tok": t.strip(), "neg": bool(m.group("neg")), "abs": bool(m.group("abs")), "sext": bool(m.group("sx"))}
343
344
345def parse(line):
346 """(op without _sdwa, [operand texts], {modifier: value}, clamp) for one SDWA line."""
347 op, _, rest = line.partition(" ")
348 if not op.endswith("_sdwa"):
349 raise RefError(f"not an SDWA line: {line!r}")
350 mods = dict(m.split(":", 1) for m in re.findall(r"\b(?:src0_sel|src1_sel|dst_sel|dst_unused):\w+", rest))
351 clamp = bool(re.search(r"\bclamp\b", rest))
352 body = re.split(r"\s+(?:clamp|src0_sel|src1_sel|dst_sel|dst_unused)\b", rest, maxsplit=1)[0]
353 return op[:-len("_sdwa")], [a.strip() for a in body.split(",")], mods, clamp
354
355
356# ---- the reference interpreter ------------------------------------------------------------------------
357
358class State:
359 def __init__(self):
360 self.v, self.s, self.vcc = {}, {}, 0
361
362
363def read_raw(st, tok, f16):
364 if tok.startswith("v") and tok[1:].isdigit():
365 return st.v.get(int(tok[1:]), 0)
366 if tok.startswith("s") and tok[1:].isdigit():
367 return st.s.get(int(tok[1:]), 0)
368 if tok in FLOAT_CONSTS:
369 return FLOAT_CONSTS_F16[tok] if f16 else FLOAT_CONSTS[tok]
370 return int(tok, 0) & M32
371
372
373def select(value, sel, sext):
374 off, w = SEL[sel]
375 v = (value >> off) & ((1 << w) - 1)
376 if sext and w < 32:
377 v = sx(v, w) & M32
378 return v
379
380
381def place(old, res, width, sel, unused):
382 off, w = SEL[sel]
383 res &= M32
384 if w == 32:
385 return res & 0xFFFF if width == 16 else res
386 field = res & ((1 << w) - 1)
387 if unused == "UNUSED_PRESERVE":
388 mask = ((1 << w) - 1) << off
389 return (old & ~mask & M32) | (field << off)
390 if unused == "UNUSED_SEXT":
391 return (sx(field, w) << off) & M32
392 return field << off
393
394
395def _clamp(kind, r):
396 if kind == "usat":
397 return max(0, min(M32, r))
398 if kind == "f16":
399 if r & 0x8000: # negative, -0 included
400 return 0
401 return min(r, 0x3C00) # +inf and anything above 1.0 (NaN results are skipped)
402 if kind == "f32":
403 if r & 0x80000000:
404 return 0
405 return min(r, 0x3F800000)
406 return r
407
408
409def step(st, line):
410 op, args, mods, clamp = parse(line)
411 if op not in OPS:
412 raise RefError(f"{op} is not modelled")
413 family, form, width, fn, clamp_kind = OPS[op]
414 if clamp and not clamp_kind:
415 raise RefError(f"{op}: clamp not modelled")
416 f16 = family == "f16"
417 srcs = args[1:3] if form in ("vop2", "vopc", "cndmask") else args[1:2]
418 vals = []
419 for i, text in enumerate(srcs):
420 s = parse_src(text)
421 v = select(read_raw(st, s["tok"], f16),
422 mods.get(f"src{i}_sel", "DWORD"), s["sext"])
423 if s["abs"]:
424 v &= ~0x8000 if f16 else ~0x80000000
425 if s["neg"]:
426 v ^= 0x8000 if f16 else 0x80000000
427 vals.append(v & M32)
428 if form == "vopc":
429 st.vcc = int(bool(fn(vals[0], vals[1])))
430 return
431 if form == "cndmask":
432 r = vals[1] if st.vcc else vals[0]
433 else:
434 r = fn(vals[0], vals[1] if len(vals) > 1 else 0)
435 r = _clamp(clamp_kind, r) if clamp else r
436 d = int(args[0][1:])
437 st.v[d] = place(st.v.get(d, 0), r, width, mods.get("dst_sel", "DWORD"), mods.get("dst_unused", "UNUSED_PAD"))
438
439
440def reference(lines):
441 """Run the program; returns the four exported words. Raises Skip for what the reference does not model."""
442 st = State()
443 for line in lines:
444 op, _, rest = line.partition(" ")
445 args = [a.strip() for a in rest.split(",")]
446 if op == "v_mov_b32":
447 st.v[int(args[0][1:])] = read_raw(st, args[1], False)
448 elif op == "s_mov_b32":
449 if args[0] == "vcc_lo":
450 st.vcc = int(args[1], 0) & 1
451 else:
452 st.s[int(args[0][1:])] = int(args[1], 0) & M32
453 elif op == "v_cndmask_b32_e64":
454 st.v[int(args[0][1:])] = int(args[2], 0) if st.vcc else int(args[1], 0)
455 else:
456 step(st, line)
457 return [st.v.get(r, 0) for r in (8, 9, 10, 11)]
458
459
460# ---- program generation -------------------------------------------------------------------------------
461
462def _word(rng):
463 r = rng.random()
464 if r < 0.35:
465 return rng.choice(INTERESTING)
466 if r < 0.7:
467 return _half(rng) | _half(rng) << 16
468 return rng.getrandbits(32)
469
470
471def _half(rng):
472 r = rng.random()
473 if r < 0.5:
474 return rng.choice(F16_INTERESTING)
475 if r < 0.65:
476 return rng.randrange(0, 0x400) | rng.choice((0, 0x8000)) # denormal
477 h = rng.getrandbits(16)
478 while is_nan16(h):
479 h = rng.getrandbits(16)
480 return h
481
482
483def _src(rng, family, allow_const=True):
484 """An operand text for a source of an op of this family."""
485 r = rng.random()
486 if r < 0.68 or not allow_const:
487 tok = f"v{rng.choice(VREGS)}" if r < 0.55 or not allow_const else f"s{rng.choice(SREGS)}"
488 elif r < 0.9:
489 tok = str(rng.choice((-16, -1, 0, 1, 2, 7, 15, 16, 24, 31, 32, 63, 64, rng.randrange(-16, 65))))
490 else:
491 return rng.choice(tuple(FLOAT_CONSTS))
492 if family == "cndmask":
493 return tok # llvm-mc takes no sext() on v_cndmask_b32_sdwa
494 if family in ("int", "int16"):
495 return f"sext({tok})" if rng.random() < 0.3 else tok
496 if not tok[0] in "vs":
497 return tok
498 if rng.random() < 0.2:
499 tok = f"|{tok}|"
500 if rng.random() < 0.25:
501 tok = "-" + tok
502 return tok
503
504
505KNOWN = False # also generate the forms in KNOWN_DIVERGENCES (--known; always on for a hardware-only run)
506SHIFTS = ("v_lshlrev_b32", "v_lshrrev_b32", "v_ashrrev_i32")
507KNOWN_DIVERGENCES = {
508 "shift-const-sel": "a constant shift amount (inline or seeded SGPR) with src0_sel or sext(): until #2005 the "
509 "translator shifts by the whole constant",
510 "dword-16bit": "a 16-bit result (f16 ops, v_cvt_{u16,i16}_f16, v_cvt_f16_{u16,i16}) with dst_sel:DWORD: the "
511 "hardware zeroes the high half, the translator keeps it",
512 "f16-const-sel": "a float inline constant with a src_sel other than DWORD in an f16 op: the hardware selects from "
513 "the f16 value (0x3c00 for 1.0), the translator reads the whole constant",
514}
515
516
517def emit(rng, name):
518 family, form, width, fn, clamp_kind = OPS[name]
519 sels = tuple(SEL)
520 s0, s1 = rng.choice(sels), rng.choice(sels)
521 if form == "vopc":
522 src1_family = "int" if name == "v_cmp_class_f16" else family
523 a, b = _src(rng, family), _src(rng, src1_family)
524 else:
525 d = f"v{rng.choice(VREGS)}"
526 clamp = " clamp" if clamp_kind and rng.random() < 0.25 else ""
527 dsel = rng.choice(sels)
528 unused = rng.choice(UNUSED)
529 a = _src(rng, "cndmask" if form == "cndmask" else family)
530 b = _src(rng, "cndmask" if form == "cndmask" else family) if form != "vop1" else None
531 if form == "cndmask" and a[0] == b[0] == "s" and a != b:
532 b = f"v{rng.choice(VREGS)}" # VCC is on the constant bus too: at most one other SGPR (gfx1030)
533 if not KNOWN:
534 inner = a[5:-1] if a.startswith("sext(") else a
535 if name in SHIFTS and inner[0] != "v":
536 s0, a = "DWORD", inner
537 if family == "f16":
538 s0 = "DWORD" if a in FLOAT_CONSTS else s0
539 s1 = "DWORD" if b in FLOAT_CONSTS and name != "v_cmp_class_f16" else s1
540 if form != "vopc" and width == 16 and dsel == "DWORD":
541 dsel = rng.choice(sels[:-1])
542 if form == "vopc":
543 return f"{name}_sdwa vcc_lo, {a}, {b} src0_sel:{s0} src1_sel:{s1}"
544 tail = f"{clamp} dst_sel:{dsel} dst_unused:{unused} src0_sel:{s0}"
545 if form == "vop1":
546 return f"{name}_sdwa {d}, {a}{tail}"
547 vcc = ", vcc_lo" if form == "cndmask" else ""
548 return f"{name}_sdwa {d}, {a}, {b}{vcc}{tail} src1_sel:{s1}"
549
550
551def seeds(rng):
552 return ([f"v_mov_b32 v{r}, 0x{_word(rng):x}" for r in VREGS] + [f"s_mov_b32 s{r}, 0x{_word(rng):x}" for r in SREGS]
553 + [f"s_mov_b32 vcc_lo, {rng.randrange(2)}"])
554
555
556def observe(regs):
557 return [f"v_mov_b32 v8, v{regs[0]}", f"v_mov_b32 v9, v{regs[1]}", f"v_mov_b32 v10, v{regs[2]}",
558 "v_cndmask_b32_e64 v11, 0, 1, vcc_lo"]
559
560
561def generate(rng, n_ops, ops):
562 body = [emit(rng, rng.choice(ops)) for _ in range(n_ops)]
563 written = []
564 for line in reversed(body):
565 d = line.split()[1].rstrip(",")
566 if d[0] == "v" and d[1:].isdigit() and d not in written:
567 written.append(d)
568 regs = [int(d[1:]) for d in written[:3]]
569 regs += rng.sample([r for r in VREGS if r not in regs], 3 - len(regs))
570 return seeds(rng) + body + observe(regs)
571
572
573# ---- the translator side ------------------------------------------------------------------------------
574
575def translated(lines, name="ps_sdwa"):
576 """Translate and execute; returns the four exported words, or raises Skip."""
577 import rdna2spirv
578 from spirv_mini_interp import run_fragment
579 with tempfile.TemporaryDirectory(prefix="sdwa-diff-") as tmp:
580 dis = os.path.join(tmp, "disasm")
581 os.mkdir(dis)
582 path = os.path.join(dis, name + ".s")
583 with open(path, "w", encoding="utf-8", newline="\n") as f:
584 f.write(f"; {name} sdwa_diff case\n")
585 for line in lines:
586 f.write("\t" + line + "\n")
587 f.write("\texp mrt0 v8, v9, v10, v11 done vm\n\ts_endpgm\n")
588 with open(os.path.join(tmp, name + ".dxbc"), "wb") as f:
589 f.write(STUB_DXBC)
590 try:
591 with warnings.catch_warnings():
592 warnings.simplefilter("ignore", ResourceWarning)
593 spvasm = rdna2spirv.translate(path)
594 gc.collect()
595 except rdna2spirv.Unsupported as e:
596 raise Skip(f"translator unsupported: {e}") from None
597 try:
598 out = run_fragment(spvasm)
599 except Exception as e: # noqa: BLE001 - an interpreter gap is a counted skip, never a pass
600 raise Skip(f"mini_interp: {type(e).__name__}: {str(e)[:80]}") from None
601 return [w & M32 for w in out["%out_mrt0"]]
602
603
604def _diff(lines, want, got, label):
605 bad = [k for k in range(4) if want[k] != got[k]]
606 if not bad:
607 return None
608 i = bad[0]
609 what = "VCC" if i == 3 else lines[-N_OBS + i].split(", ")[1]
610 return f"word {i} ({what}): reference 0x{want[i]:08x}, {label} 0x{got[i]:08x}"
611
612
613def check(lines, backends=("translator",), hw=None):
614 """None on a match, else a description. Raises Skip (the reference or every backend skipped) / RefError.
615 hw is the hardware result for this program (four words or a str reason), or a callable lines -> that."""
616 want = reference(lines)
617 problems, skips = [], []
618 if "translator" in backends:
619 try:
620 problems.append(_diff(lines, want, translated(lines), "translated"))
621 except Skip as e:
622 skips.append(e)
623 if "hw" in backends:
624 got = hw(lines) if callable(hw) else hw
625 if isinstance(got, str):
626 skips.append(Skip(f"hardware: {got}"))
627 else:
628 problems.append(_diff(lines, want, got, "hardware"))
629 if skips and len(skips) == len(backends):
630 raise skips[0]
631 return "; ".join(p for p in problems if p) or None
632
633
634def shrink(lines, check_fn=check):
635 """Drop instructions (not the seeds or the observation) while the program still mismatches."""
636 body = lines[N_SEED:-N_OBS]
637 changed = True
638 while changed:
639 changed = False
640 for i in range(len(body)):
641 trial = lines[:N_SEED] + body[:i] + body[i + 1:] + lines[-N_OBS:]
642 try:
643 if check_fn(trial):
644 body = body[:i] + body[i + 1:]
645 changed = True
646 break
647 except (Skip, RefError):
648 continue
649 return lines[:N_SEED] + body + lines[-N_OBS:]
650
651
652def hw_prepare(oracle, programs):
653 """Run every program on the hardware in batches. Returns per program the four words, or a str reason."""
654 return oracle.run(programs)
655
656
657def run_suite(programs, seed, max_ops, ops, backends=("translator",), oracle=None):
658 counts = {"pass": 0, "mismatch": 0, "skip": {}}
659 failures = []
660 rng = random.Random(seed)
661 progs = [generate(rng, rng.randrange(1, max_ops + 1), ops) for _ in range(programs)]
662 hw_words = hw_prepare(oracle, progs) if "hw" in backends else [None] * programs
663 for i, lines in enumerate(progs):
664 try:
665 problem = check(lines, backends, hw_words[i])
666 except Skip as e:
667 counts["skip"][str(e)] = counts["skip"].get(str(e), 0) + 1
668 continue
669 if problem is None:
670 counts["pass"] += 1
671 continue
672 counts["mismatch"] += 1
673 failures.append((i, problem, lines))
674 return counts, failures
675
676
677def self_test():
678 base = [f"v_mov_b32 v{r}, 0x{0x11111111 * r:x}" for r in VREGS] + [f"s_mov_b32 s{r}, {r}" for r in SREGS]
679 base.append("s_mov_b32 vcc_lo, 0")
680 ok = check(base + ["v_add_nc_u32_sdwa v1, v2, v3 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE "
681 "src0_sel:BYTE_1 src1_sel:WORD_0"] + observe([1, 2, 3])) is None
682 # 0x2222 + 0x33 = 0x2255 into the high word of v1 (0x11111111): 0x22551111
683 placed = reference(base + ["v_add_nc_u32_sdwa v1, v2, v3 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE "
684 "src0_sel:WORD_0 src1_sel:BYTE_0"] + observe([1, 2, 3]))[0] == 0x22551111
685 try:
686 translated(base + ["v_add_nc_u32_dpp v1, v2, v3 quad_perm:[0,0,0,0] row_mask:0xf bank_mask:0xf"
687 .replace("_dpp", "_sdwa_dpp")] + observe([1, 2, 3]))
688 skipped = False
689 except Skip:
690 skipped = True
691 print(f"self-test: match {ok}, placement modelled {placed}, unsupported form skipped {skipped}")
692 return ok and placed and skipped
693
694
695def main(argv=None):
696 ap = argparse.ArgumentParser(description="SDWA VOP1/VOP2/VOPC differential fuzzing.")
697 ap.add_argument("--programs", type=int, default=300)
698 ap.add_argument("--seed", type=int, default=1)
699 ap.add_argument("--max-ops", type=int, default=4)
700 ap.add_argument("--ops", default=None, help="comma-separated opcodes without _sdwa (default: the --family ones)")
701 ap.add_argument("--family", default="all", choices=("int", "f16", "all"))
702 ap.add_argument("--list-ops", action="store_true")
703 ap.add_argument("--self-test", action="store_true")
704 ap.add_argument("--all-failures", action="store_true", help="print every failing program, not just the first")
705 ap.add_argument("--oracle", default="translator",
706 help="comma-separated comparison targets: translator (default), hw (natively on an RDNA1/RDNA2 "
707 "GPU; see tools/hw_oracle/). 'hw' alone compares the hardware with the reference only")
708 ap.add_argument("--hw-arch", default=None, help="GPU architecture to assemble for (default: detected)")
709 ap.add_argument("--known", action="store_true",
710 help="also generate the forms where the translator is known to differ (KNOWN_DIVERGENCES; "
711 "always on with --oracle hw alone)")
712 a = ap.parse_args(argv)
713 if a.programs < 1 or a.max_ops < 1:
714 ap.error("--programs and --max-ops must be at least 1")
715 backends = tuple(dict.fromkeys(t.strip() for t in a.oracle.split(",")))
716 if not backends or any(t not in ("translator", "hw") for t in backends):
717 ap.error("--oracle takes translator, hw or translator,hw")
718 global KNOWN
719 KNOWN = a.known or backends == ("hw",)
720 if a.list_ops:
721 for name in sorted(OPS):
722 family, form, width, _, clamp = OPS[name]
723 print(f"{name:20} {'f16' if family == 'f16' else 'int'} {form}{' clamp' if clamp else ''}")
724 return 0
725 if a.self_test:
726 return 0 if self_test() else 1
727 if a.ops is not None:
728 tokens = [t.strip() for t in a.ops.split(",")]
729 if not any(tokens) or any(not t for t in tokens):
730 ap.error("--ops must be a comma-separated list of opcodes")
731 ops = sorted(set(tokens))
732 else:
733 ops = sorted(o for o, v in OPS.items()
734 if a.family == "all" or (a.family == "f16") == (v[0] == "f16"))
735 unknown = [o for o in ops if o not in OPS]
736 if unknown:
737 ap.error("unknown ops: " + ", ".join(unknown))
738 oracle = None
739 if "hw" in backends:
740 from hw_oracle import asm, runner
741 try:
742 oracle = runner.open_oracle(arch=a.hw_arch)
743 except runner.Unavailable as e:
744 print(f"hardware oracle unavailable: {e}")
745 return 77
746 if asm.family(oracle.arch) != "gfx10":
747 print(f"hardware oracle unavailable: {oracle.arch} has no SDWA (GFX9 and GFX10 only)")
748 oracle.close()
749 return 77
750 print(f"hardware oracle: {oracle.device}")
751 try:
752 counts, failures = run_suite(a.programs, a.seed, a.max_ops, ops, backends, oracle)
753 skips = sum(counts["skip"].values())
754 print(f"{a.programs} programs (seed {a.seed}, {'+'.join(backends)}): {counts['pass']} pass, "
755 f"{counts['mismatch']} mismatch, {skips} skipped")
756 for reason, n in sorted(counts["skip"].items(), key=lambda kv: -kv[1]):
757 print(f" skip x{n}: {reason}")
758
759 def check_fn(lines):
760 return check(lines, backends, (lambda l: oracle.run([l])[0]) if oracle else None)
761 for i, problem, lines in failures[: None if a.all_failures else 1]:
762 small = shrink(lines, check_fn)
763 print(f"MISMATCH program {i}: {check_fn(small) or problem}")
764 print("\n".join("\t" + line for line in small))
765 except (RefError, RuntimeError) as e:
766 print(f"harness error: {e}")
767 return 2
768 finally:
769 if oracle:
770 oracle.close()
771 return 1 if failures else 0
772
773
774if __name__ == "__main__":
775 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
776 sys.stdout.reconfigure(errors="replace")
777 except (AttributeError, ValueError, OSError):
778 pass
779 sys.exit(main())
diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py
index 38f49e7a6..9b9abfd70 100644
--- a/tools/shader_disasm.py
+++ b/tools/shader_disasm.py
@@ -6,7 +6,7 @@ The code ends with s_endpgm (0xBF810000). If the header guess doesn't hold for a
6scanning back from the first s_endpgm to the start that decodes with no invalid instructions. 6scanning back from the first s_endpgm to the start that decodes with no invalid instructions.
7 7
8Usage: 8Usage:
9 python -I shader_disasm.py <fssm dir or file> [--out DIR] [--mcpu gfx1013] [--limit N] 9 python -I shader_disasm.py <fssm dir or file> [--unpack-index FILE] [--out DIR] [--mcpu gfx1013] [--limit N]
10Writes <out>/<name>.s and prints a summary (decoded cleanly / with invalid words / failed). 10Writes <out>/<name>.s and prints a summary (decoded cleanly / with invalid words / failed).
11Set LLVM_MC to llvm-mc's path, or to a whole command such as 11Set LLVM_MC to llvm-mc's path, or to a whole command such as
12'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' when the tool is not on PATH. 12'wsl -d Ubuntu -e /usr/lib/llvm-21/bin/llvm-mc' when the tool is not on PATH.
@@ -20,6 +20,7 @@ from concurrent.futures import ThreadPoolExecutor
20 20
21sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) 21sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
22from mc_command import mc_command # noqa: E402 22from mc_command import mc_command # noqa: E402
23from shader_stage_manifest import shader_stems # noqa: E402
23 24
24TRIPLE = "amdgcn--amdpal" 25TRIPLE = "amdgcn--amdpal"
25ENDPGM = b"\x00\x00\x81\xbf" 26ENDPGM = b"\x00\x00\x81\xbf"
@@ -130,17 +131,30 @@ def one(path, out, mcpu):
130def main(): 131def main():
131 ap = argparse.ArgumentParser() 132 ap = argparse.ArgumentParser()
132 ap.add_argument("src") 133 ap.add_argument("src")
134 ap.add_argument("--unpack-index", help="disassemble only the FSSMs listed in this unpack index")
133 ap.add_argument("--out") 135 ap.add_argument("--out")
134 ap.add_argument("--mcpu", default="gfx1013") 136 ap.add_argument("--mcpu", default="gfx1013")
135 ap.add_argument("--limit", type=positive_int) 137 ap.add_argument("--limit", type=positive_int)
136 ap.add_argument("--jobs", type=positive_int, default=max(1, (os.cpu_count() or 2) // 2)) 138 ap.add_argument("--jobs", type=positive_int, default=max(1, (os.cpu_count() or 2) // 2))
137 a = ap.parse_args() 139 a = ap.parse_args()
138 if os.path.isfile(a.src): 140 if os.path.isfile(a.src):
141 if a.unpack_index:
142 ap.error("--unpack-index requires an FSSM directory")
139 files = [a.src] 143 files = [a.src]
140 elif os.path.isdir(a.src): 144 elif os.path.isdir(a.src):
141 with os.scandir(a.src) as entries: 145 try:
142 files = sorted(entry.path for entry in entries 146 if a.unpack_index:
143 if entry.name.endswith(".fssm") and entry.is_file()) 147 names = shader_stems(a.unpack_index, "name")
148 files = sorted(os.path.join(a.src, name + ".fssm") for name in names)
149 for path in files:
150 if not os.path.isfile(path):
151 raise ValueError(f"{a.unpack_index}: declared FSSM file is missing: {path}")
152 else:
153 with os.scandir(a.src) as entries:
154 files = sorted(entry.path for entry in entries
155 if entry.name.endswith(".fssm") and entry.is_file())
156 except (OSError, ValueError) as e:
157 fail(f"cannot list shaders in {a.src}: {e}")
144 else: 158 else:
145 fail(f"{a.src} is not a file or folder") 159 fail(f"{a.src} is not a file or folder")
146 if not files: 160 if not files:
diff --git a/tools/shader_ir.py b/tools/shader_ir.py
index 1ad2a00c9..ca3e04ce8 100644
--- a/tools/shader_ir.py
+++ b/tools/shader_ir.py
@@ -192,6 +192,12 @@ def parse_line(line):
192 if parts and len(parts[0].split()) == 2: 192 if parts and len(parts[0].split()) == 2:
193 parts = parts[0].split() + parts[1:] 193 parts = parts[0].split() + parts[1:]
194 args = [operand(a) for a in parts] 194 args = [operand(a) for a in parts]
195 if op.startswith(("v_add_f64", "v_cvt_f32_f64")):
196 for src, spelling in zip(args[1:], parts[1:]):
197 # LLVM prints inline integers in decimal and the separate literal dword in hex,
198 # even for two sources with the same numeric value (e.g. 0x1 and 1).
199 if src["k"] == "imm" and ("0x" in spelling or not -16 <= src["v"] <= 64):
200 src["f64_literal"] = True
195 return {"op": op, "args": args, "mods": mods, "enc": enc.hex() if enc else None} 201 return {"op": op, "args": args, "mods": mods, "enc": enc.hex() if enc else None}
196 202
197 203
diff --git a/tools/shader_stage_manifest.py b/tools/shader_stage_manifest.py
new file mode 100644
index 000000000..39b6cf0ad
--- /dev/null
+++ b/tools/shader_stage_manifest.py
@@ -0,0 +1,20 @@
1"""Read shader names from a completed carve or unpack index."""
2
3import json
4import ntpath
5
6
7def shader_stems(path: str, field: str, suffix: str = "") -> set[str]:
8 with open(path, encoding="utf-8") as f:
9 rows = json.load(f)
10 if not isinstance(rows, list):
11 raise ValueError(f"{path}: expected an array of shader entries")
12 stems = set()
13 for row in rows:
14 value = row.get(field) if isinstance(row, dict) else None
15 if not isinstance(value, str) or not value or value in (".", "..") or ntpath.basename(value) != value:
16 raise ValueError(f"{path}: expected a shader basename in {field!r}")
17 if suffix and (not value.endswith(suffix) or len(value) == len(suffix)):
18 raise ValueError(f"{path}: expected a {suffix} filename in {field!r}")
19 stems.add(value.removesuffix(suffix))
20 return stems
diff --git a/tools/skin_streams.py b/tools/skin_streams.py
index db5adcfcc..82c9da3ee 100644
--- a/tools/skin_streams.py
+++ b/tools/skin_streams.py
@@ -325,12 +325,15 @@ def validate(mesh, gfx, layout):
325 t["weighted-components"] += 1 325 t["weighted-components"] += 1
326 if idx >= mesh.bones: 326 if idx >= mesh.bones:
327 t["components-out-of-range"] += 1 327 t["components-out-of-range"] += 1
328 else: # 4-byte index rows, masked by the matching weight row 328 else: # four 8-bit or 16-bit indices per vertex, masked by the matching weights
329 wide = len(row) == 8 * n
329 for v in range(n): 330 for v in range(n):
330 for c in range(4): 331 base = 4 * v
331 if weights is None or weights[4 * v + c]: 332 joints = struct.unpack_from("<4H", row, 2 * base) if wide else row[base:base + 4]
333 for c, joint in enumerate(joints):
334 if weights is None or weights[base + c]:
332 t["weighted-components"] += 1 335 t["weighted-components"] += 1
333 if row[4 * v + c] >= mesh.bones: 336 if joint >= mesh.bones:
334 t["components-out-of-range"] += 1 337 t["components-out-of-range"] += 1
335 return t 338 return t
336 339
diff --git a/tools/skinned_glb.py b/tools/skinned_glb.py
new file mode 100644
index 000000000..4222f9f26
--- /dev/null
+++ b/tools/skinned_glb.py
@@ -0,0 +1,938 @@
1"""Export a skinned GLB from a decoded RAGE pack model and its 8-influence skin streams.
2
3Usage::
4
5 python -I tools/skinned_glb.py out.glb \\
6 --skeleton ambient_femalebody/model.json \\
7 --component head/model.json \\
8 --component jacket/model.json
9
10Inputs are read-only decoded pack directories: ``model.json``, its ``model.glb``
11geometry, and the graphics buffer named by ``buffer_files``. Nothing is written
12except the output GLB; no source bytes are copied into the repository.
13
14Source layout (measured on the 1.0.2.1 package)
15------------------------------------------------
16
17The vertex skin streams are 4-byte elements at the offsets below, relative to the
18start of the graphics buffer (``buffers/01_0.bin`` for both measured components).
19Each section word in the 23-word mesh-block header encodes
20``offset = (word >> 8) * 2`` and ``format = word & 0xFF``; the same triples are
21also present in ``drawable.buffers[vertex_buffer].mesh_blob.sections`` as
22``[semantic, offset, format]``.
23
24===== ===== ============================== ======== ========== =====
25Mesh Slot Meaning Offset Format Bytes
26===== ===== ============================== ======== ========== =====
27head 8 JOINTS_0, 4 x u8 215,720 0x25 35,932
28head 9 JOINTS_1, 4 x u8 251,652 0x25 35,932
29head 6 WEIGHTS_0, 4 x u8 UNORM 143,856 0x26 35,932
30head 7 WEIGHTS_1, 4 x u8 UNORM 179,788 0x26 35,932
31jacket 8 JOINTS_0 275,032 0x25 39,272
32jacket 9 JOINTS_1 314,304 0x25 39,272
33jacket 6 WEIGHTS_0 196,488 0x26 39,272
34jacket 7 WEIGHTS_1 235,760 0x26 39,272
35===== ===== ============================== ======== ========== =====
36
37The joint index is local to the drawable model's own palette: a sorted ``u32``
38joaat32 array at ``grmModel + 0x20`` with its length at ``grmModel + 0x0C``. The
39ped skeleton bind pose is ``drawable.skeleton[].bind_matrix`` from a decoded
40skeleton resource (bone -> model, column-major, RAGE Z-up). Palette hashes are
41resolved against the drawable's own skeleton/string table and then the ped
42skeleton; a hash that resolves nowhere is emitted as ``bone_0x........``.
43
44Output has one skin. Its joints are the full ped skeleton plus any drawable-local
45helper joints named by the palette. Every vertex keeps all eight influences as
46``JOINTS_0``/``JOINTS_1`` (UNSIGNED_SHORT VEC4) and
47``WEIGHTS_0``/``WEIGHTS_1`` (FLOAT VEC4). Source weights are u8 values that sum
48to 255; they are normalised to 1.0. Bind matrices and inverse bind matrices use
49the same RAGE Z-up -> glTF Y-up conversion as positions, ``(x, y, z) -> (x, z, -y)``.
50
51Only skinned primitives are exported, with clay materials. Textures, UV atlas
52data and materials of the source package are not copied. This is a static export
53path: it does not assemble a body or any other unrequested component.
54"""
55from __future__ import annotations
56
57import argparse
58import json
59import math
60import os
61import struct
62import sys
63
64try: # optional: the stdlib path below is the fallback and is covered by the tests
65 import numpy as _np
66except ImportError: # pragma: no cover - depends on the interpreter
67 _np = None
68
69GLB_MAGIC = b"glTF"
70GLB_VERSION = 2
71CHUNK_JSON = 0x4E4F534A
72CHUNK_BIN = 0x004E4942
73ARRAY_BUFFER = 34962
74ELEMENT_ARRAY_BUFFER = 34963
75MODE_TRIANGLES = 4
76
77COMPONENT_BYTE = 5121
78COMPONENT_UNSIGNED_SHORT = 5123
79COMPONENT_UNSIGNED_INT = 5125
80COMPONENT_FLOAT = 5126
81
82JOINT_SLOTS = (8, 9)
83WEIGHT_SLOTS = (6, 7)
84INDEX_FORMAT = 0x25 # R8G8B8A8_UINT, one 4-byte element per vertex
85WEIGHT_FORMAT = 0x26 # R8G8B8A8_UNORM
86COMPONENT_SIZES = {5120: 1, 5121: 1, 5122: 2, 5123: 2, 5125: 4, 5126: 4}
87TYPE_COMPONENTS = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT4": 16}
88
89# RAGE Z-up -> glTF Y-up: (x, y, z) -> (x, z, -y).
90_YUP = ((1.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, -1.0, 0.0))
91
92# Attribute names copied from the decoded model.glb. Skin attributes are rebuilt
93# from the source streams; custom private attributes are not needed for display.
94GEOMETRY_ATTRIBUTES = (
95 "POSITION", "NORMAL", "TANGENT",
96 "TEXCOORD_0", "TEXCOORD_1", "TEXCOORD_2", "TEXCOORD_3",
97 "TEXCOORD_4", "TEXCOORD_5", "TEXCOORD_6", "TEXCOORD_7",
98 "COLOR_0",
99)
100
101_ORIENTATION = {"O", "I", "F", "B", "CF", "CB", "LF", "LB", "RF", "RB"}
102_SIDES = {"L", "R", "C"}
103
104
105class SkinError(ValueError):
106 """A decoded model or skin stream is missing, inconsistent or out of range."""
107
108
109# --------------------------------------------------------------------------- math
110def joaat32(name: str) -> int:
111 """RAGE joaat32 over the lowercased Latin-1 bytes of a bone name."""
112 value = 0
113 for byte in name.lower().encode("latin-1", "replace"):
114 value = (value + byte) & 0xFFFFFFFF
115 value = (value + (value << 10)) & 0xFFFFFFFF
116 value ^= value >> 6
117 value = (value + (value << 3)) & 0xFFFFFFFF
118 value ^= value >> 11
119 return (value + (value << 15)) & 0xFFFFFFFF
120
121
122def mat_mul(a, b):
123 """Column-major 4x4 product ``a * b``."""
124 out = [0.0] * 16
125 for column in range(4):
126 for row in range(4):
127 out[column * 4 + row] = sum(a[k * 4 + row] * b[column * 4 + k] for k in range(4))
128 return out
129
130
131def invert_affine(m):
132 """Inverse of a column-major affine 4x4 (bottom row 0, 0, 0, 1)."""
133 a = lambda row, column: m[column * 4 + row]
134 det = (a(0, 0) * (a(1, 1) * a(2, 2) - a(1, 2) * a(2, 1))
135 - a(0, 1) * (a(1, 0) * a(2, 2) - a(1, 2) * a(2, 0))
136 + a(0, 2) * (a(1, 0) * a(2, 1) - a(1, 1) * a(2, 0)))
137 if not math.isfinite(det) or abs(det) < 1e-12:
138 raise SkinError("singular or non-finite bind matrix")
139 k = 1.0 / det
140 cofactors = (
141 (a(1, 1) * a(2, 2) - a(1, 2) * a(2, 1)) * k,
142 (a(0, 2) * a(2, 1) - a(0, 1) * a(2, 2)) * k,
143 (a(0, 1) * a(1, 2) - a(0, 2) * a(1, 1)) * k,
144 (a(1, 2) * a(2, 0) - a(1, 0) * a(2, 2)) * k,
145 (a(0, 0) * a(2, 2) - a(0, 2) * a(2, 0)) * k,
146 (a(0, 2) * a(1, 0) - a(0, 0) * a(1, 2)) * k,
147 (a(1, 0) * a(2, 1) - a(1, 1) * a(2, 0)) * k,
148 (a(0, 1) * a(2, 0) - a(0, 0) * a(2, 1)) * k,
149 (a(0, 0) * a(1, 1) - a(0, 1) * a(1, 0)) * k,
150 )
151 tx, ty, tz = a(0, 3), a(1, 3), a(2, 3)
152 out = [0.0] * 16
153 for row in range(3):
154 for column in range(3):
155 out[column * 4 + row] = cofactors[row * 3 + column]
156 out[12 + row] = -(cofactors[row * 3] * tx
157 + cofactors[row * 3 + 1] * ty
158 + cofactors[row * 3 + 2] * tz)
159 out[15] = 1.0
160 return out
161
162
163def bind_to_gltf(m):
164 """Convert a column-major RAGE Z-up matrix to glTF Y-up: ``C * M * C^T``."""
165 a = lambda row, column: m[column * 4 + row]
166 out = [0.0] * 16
167 for row in range(3):
168 for column in range(3):
169 out[column * 4 + row] = sum(
170 _YUP[row][i] * a(i, j) * _YUP[column][j]
171 for i in range(3) for j in range(3)
172 )
173 out[12 + row] = sum(_YUP[row][i] * a(i, 3) for i in range(3))
174 out[15] = 1.0
175 return out
176
177
178def _identity() -> list[float]:
179 return [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]
180
181
182def _is_identity(m) -> bool:
183 return all(abs(v - (1.0 if i in (0, 5, 10, 15) else 0.0)) <= 1e-9 for i, v in enumerate(m))
184
185
186def _finite_matrix(m) -> bool:
187 return len(m) == 16 and all(isinstance(v, (int, float)) and math.isfinite(v) for v in m)
188
189
190# ------------------------------------------------------------------------ files
191def _load_json(path: str) -> dict:
192 with open(path, encoding="utf-8") as handle:
193 value = json.load(handle)
194 if not isinstance(value, dict):
195 raise SkinError(f"{path}: model.json root is not an object")
196 return value
197
198
199def model_json_path(path: str) -> tuple[str, str]:
200 """Return ``(directory, model.json path)`` for a decoded pack directory or file."""
201 if os.path.isdir(path):
202 return path, os.path.join(path, "model.json")
203 if os.path.isfile(path) and os.path.basename(path).lower().endswith(".json"):
204 return os.path.dirname(os.path.abspath(path)), path
205 raise SkinError(f"{path}: expected a decoded model directory or its model.json")
206
207
208def read_skin_streams(model_dir: str, model: dict, mesh: dict) -> dict:
209 """Read one mesh's JOINTS_0/1 and WEIGHTS_0/1 streams.
210
211 Returns the four raw byte rows plus the vertex count, local palette length and
212 measured section table. The caller still maps local indices to GLB joints.
213 """
214 drawable = model.get("drawable")
215 if not isinstance(drawable, dict):
216 raise SkinError("model.json has no drawable object")
217 meshes = model.get("meshes")
218 if not isinstance(meshes, list):
219 raise SkinError("model.json has no meshes list")
220 try:
221 geometry = drawable["geometries"][mesh["geometry"]]
222 vertex_buffer_index = geometry["vertex_buffer"]
223 vertex_buffer = drawable["buffers"][vertex_buffer_index]
224 model_record = drawable["models"][mesh["model"]]
225 except (KeyError, IndexError, TypeError) as exc:
226 raise SkinError(f"mesh links to a missing drawable record: {exc}") from exc
227
228 palette = model_record.get("bone_palette")
229 if not isinstance(palette, list) or not palette:
230 raise SkinError("model has no bone palette")
231 if not all(isinstance(v, int) and 0 <= v <= 0xFFFFFFFF for v in palette):
232 raise SkinError("bone palette must be u32 hashes")
233
234 buffer_name = model.get("buffer_files", [])
235 try:
236 buffer_file = buffer_name[vertex_buffer_index]
237 except (IndexError, TypeError) as exc:
238 raise SkinError("vertex buffer has no buffer_files entry") from exc
239 buffer_path = os.path.join(model_dir, buffer_file)
240 with open(buffer_path, "rb") as handle:
241 blob = handle.read()
242
243 base = int(vertex_buffer.get("gfx_off", 0) or 0)
244 if base < 0 or base > len(blob):
245 raise SkinError("vertex buffer offset is outside its buffer")
246
247 sections = {}
248 mesh_blob = vertex_buffer.get("mesh_blob")
249 raw_sections = mesh_blob.get("sections") if isinstance(mesh_blob, dict) else None
250 if raw_sections:
251 for row in raw_sections:
252 if not isinstance(row, (list, tuple)) or len(row) != 3:
253 raise SkinError("mesh_blob.sections entries must be [semantic, offset, format]")
254 semantic, offset, fmt = (int(v) for v in row)
255 sections[semantic] = (offset, fmt)
256 else:
257 for semantic in range(23):
258 word = struct.unpack_from("<I", blob, base + semantic * 4)[0]
259 if word:
260 sections[semantic] = ((word >> 8) * 2, word & 0xFF)
261
262 for slot in (6, 8):
263 if slot not in sections:
264 raise SkinError(f"missing skin stream slot {slot}")
265 if (9 in sections) != (7 in sections):
266 raise SkinError("JOINTS_1 and WEIGHTS_1 must be present together")
267
268 vertex_count = mesh.get("vertex_count", model.get("vertex_count"))
269 if not isinstance(vertex_count, int) or vertex_count <= 0:
270 raise SkinError("mesh has no positive vertex_count")
271
272 rows = {}
273 for slot in (6, 7, 8, 9):
274 if slot not in sections:
275 continue
276 offset, fmt = sections[slot]
277 expected = WEIGHT_FORMAT if slot in WEIGHT_SLOTS else INDEX_FORMAT
278 if fmt != expected:
279 raise SkinError(
280 f"skin stream slot {slot} has format 0x{fmt:02x}; expected 0x{expected:02x}"
281 )
282 start = base + offset
283 end = start + 4 * vertex_count
284 if start < base or end > len(blob):
285 raise SkinError(f"skin stream slot {slot} is outside its graphics buffer")
286 rows[slot] = blob[start:end]
287
288 return {
289 "j0": rows[8],
290 "j1": rows.get(9, bytes(4 * vertex_count)),
291 "w0": rows[6],
292 "w1": rows.get(7, bytes(4 * vertex_count)),
293 "count": vertex_count,
294 "local_bones": len(palette),
295 "sections": sections,
296 "palette": palette,
297 }
298
299
300# ---------------------------------------------------------------------- skeleton
301def _bone_name_map(skeleton) -> tuple[dict[str, dict], dict[int, dict]]:
302 if not isinstance(skeleton, list) or not skeleton:
303 raise SkinError("skeleton has no bones")
304 by_name, by_hash = {}, {}
305 for bone in skeleton:
306 name = bone.get("name")
307 if not isinstance(name, str) or not name:
308 raise SkinError("skeleton bone has no name")
309 if not _finite_matrix(bone.get("bind_matrix")):
310 raise SkinError(f"skeleton bone {name!r} has no finite bind matrix")
311 by_name.setdefault(name, bone)
312 by_hash.setdefault(joaat32(name), bone)
313 return by_name, by_hash
314
315
316class JointSet:
317 """Ped joints followed by drawable-local helper joints, with bind-pose worlds."""
318
319 def __init__(self, ped_skeleton):
320 self.ped_by_name, _ = _bone_name_map(ped_skeleton)
321 self.ped_count = len(ped_skeleton)
322 self.names: list[str] = []
323 self.binds: list[list[float]] = []
324 self.parents: list[int | None] = []
325 self._by_name: dict[str, int] = {}
326
327 roots = [i for i, bone in enumerate(ped_skeleton) if bone.get("parent") is None]
328 if not roots:
329 raise SkinError("ped skeleton has no root bone")
330 self.root = roots[0]
331 for index, bone in enumerate(ped_skeleton):
332 bind = bind_to_gltf(bone["bind_matrix"])
333 parent = bone.get("parent")
334 if not isinstance(parent, int) or not 0 <= parent < len(ped_skeleton):
335 parent = None if index == self.root else self.root
336 self.names.append(bone["name"])
337 self.binds.append(bind)
338 self.parents.append(parent)
339 self._by_name.setdefault(bone["name"], index)
340
341 @property
342 def count(self) -> int:
343 return len(self.names)
344
345 def find(self, name: str) -> int | None:
346 return self._by_name.get(name)
347
348 def add(self, name: str, bind: list[float], parent: int) -> int:
349 if not _finite_matrix(bind):
350 raise SkinError(f"joint {name!r} has a non-finite bind matrix")
351 if not 0 <= parent < self.count:
352 raise SkinError(f"joint {name!r} has an invalid parent")
353 existing = self._by_name.get(name)
354 if existing is not None:
355 return existing
356 index = len(self.names)
357 self.names.append(name)
358 self.binds.append(bind)
359 self.parents.append(parent)
360 self._by_name[name] = index
361 return index
362
363 def local_matrix(self, index: int) -> list[float]:
364 parent = self.parents[index]
365 if parent is None:
366 return list(self.binds[index])
367 return mat_mul(invert_affine(self.binds[parent]), self.binds[index])
368
369 def inverse_bind(self, index: int) -> list[float]:
370 return invert_affine(self.binds[index])
371
372
373def _normalise_tokens(name: str) -> tuple[list[str], str | None]:
374 """Name tokens and side, with the drawable prefix and orientation suffixes removed."""
375 upper = name.upper()
376 for prefix in ("GM_U01_", "EGM_U01_", "SKEL_", "BM_", "MH_", "RB_", "HH_", "PH_", "EO_", "IK_", "OH_"):
377 if upper.startswith(prefix):
378 upper = upper[len(prefix):]
379 break
380 tokens = [part for part in upper.split("_") if part]
381 while tokens and tokens[-1] in _ORIENTATION:
382 tokens.pop()
383 side = next((part for part in tokens if part in _SIDES), None)
384 return tokens, side
385
386
387def _ped_tokens(name: str) -> tuple[list[str], str | None]:
388 return _normalise_tokens(name)
389
390
391def _alias_tokens(tokens: list[str], side: str | None) -> set[str]:
392 aliases = set()
393 for token in tokens:
394 base = token.rstrip("0123456789")
395 digits = token[len(base):]
396 if "UPPERARM" in base:
397 aliases.add("UPPERARM")
398 elif "FOREARM" in base:
399 aliases.add("FOREARM")
400 elif "ELBOW" in base:
401 aliases.add("FOREARM")
402 elif "DELT" in base or "ARMPIT" in base:
403 aliases.add("UPPERARM")
404 elif "THIGH" in base:
405 aliases.add("PELVIS" if side == "C" else "THIGH")
406 elif "TRAP" in base:
407 aliases.add("CLAVICLE" if side in ("L", "R") else "SPINE6")
408 elif base == "PELVIS":
409 aliases.add("PELVIS")
410 elif base == "CLAVICLE":
411 aliases.add("CLAVICLE")
412 elif base == "NECK" and digits.isdigit():
413 aliases.add(token) # Neck0 .. Neck2 are distinct deform bones
414 elif base == "SPINE" and digits.isdigit():
415 aliases.add(token) # Spine0 .. Spine6 are distinct deform bones
416 return aliases
417
418
419def infer_ped_parent(name: str, ped_by_name: dict[str, dict]) -> int | None:
420 """Pick the ped bone a drawable-local helper covers, by name tokens.
421
422 Garment helpers such as ``GM_*_L_UpperArm01_CF`` carry no hierarchy of their
423 own in the measured resources. The helper is attached to the deform bone with
424 the matching side and body-part token; anatomy aliases cover common helper
425 spellings (delt/armpit -> upper arm, elbow -> forearm, side trap -> clavicle,
426 centre trap -> spine6). The fallback is the first deform bone.
427 """
428 tokens, side = _ped_tokens(name)
429 aliases = _alias_tokens(tokens, side)
430 best: tuple[int, int, int, int] | None = None
431 for index, bone in enumerate(ped_by_name.values()):
432 ped_name = bone["name"]
433 if not ped_name.upper().startswith("SKEL_"):
434 continue
435 ped_tokens, ped_side = _ped_tokens(ped_name)
436 if side in ("L", "R") and ped_side in ("L", "R") and side != ped_side:
437 continue
438 if side == "C" and ped_side in ("L", "R"):
439 continue
440 ped_set = set(ped_tokens)
441 score = 0
442 for alias in aliases:
443 if alias in ped_set:
444 score += 10
445 elif any(token.startswith(alias.lower()) for token in ped_set):
446 score += 5
447 if score:
448 candidate = (score, -len(ped_name), -index, index)
449 if best is None or candidate > best:
450 best = candidate
451 if best is not None:
452 return best[3]
453 for index, bone in enumerate(ped_by_name.values()):
454 if bone["name"].upper().startswith("SKEL_"):
455 return index
456 return None
457
458
459class PaletteResolver:
460 """joaat32 palette -> bone name, using the drawable tables before the ped table."""
461
462 def __init__(self, component: dict, ped_by_name: dict[str, dict]):
463 self.ped_by_name = ped_by_name
464 drawable = component.get("drawable") or {}
465 own = drawable.get("skeleton") or []
466 self.own_skeleton = own
467 self.own_by_name = {}
468 self.by_hash: dict[int, tuple[str, str]] = {}
469 for bone in own:
470 name = bone.get("name")
471 if isinstance(name, str) and name:
472 self.own_by_name.setdefault(name, bone)
473 self.by_hash.setdefault(joaat32(name), (name, "own"))
474 for text in drawable.get("strings") or []:
475 if not isinstance(text, str) or not text:
476 continue
477 self._add_string(text, "string")
478 # The measured string table has one entry with a stray leading
479 # character (EGM_... for the GM_... palette hash). Index that alias
480 # only when the unstripped spelling did not already claim the hash.
481 if len(text) > 2 and text[0].isalpha() and text[1].isupper():
482 self._add_string(text[1:], "alias", only_if_absent=True)
483 for name, bone in ped_by_name.items():
484 self.by_hash.setdefault(joaat32(name), (name, "ped"))
485
486 def _add_string(self, text: str, source: str, only_if_absent: bool = False) -> None:
487 key = joaat32(text)
488 if only_if_absent and key in self.by_hash:
489 return
490 self.by_hash.setdefault(key, (text, source))
491
492 def resolve(self, value: int) -> tuple[str, str]:
493 found = self.by_hash.get(value)
494 if found is None:
495 return f"bone_0x{value:08x}", "fallback"
496 return found
497
498
499# --------------------------------------------------------------------- weights
500def normalise_weights(j0: bytes, j1: bytes, w0: bytes, w1: bytes, count: int,
501 local_bones: int, local_to_joint: list[int],
502 joint_count: int | None = None) -> dict:
503 """Map local joint bytes to GLB joints and normalise every 8-weight row to 1.0."""
504 if count <= 0 or local_bones <= 0:
505 raise SkinError("skin stream has no vertices or no local bones")
506 if len(local_to_joint) != local_bones:
507 raise SkinError("joint palette map has the wrong length")
508 if any(not isinstance(v, int) or v < 0 or
509 (joint_count is not None and v >= joint_count) for v in local_to_joint):
510 raise SkinError("joint palette map contains an invalid joint index")
511 expected = 4 * count
512 for row in (j0, j1, w0, w1):
513 if len(row) != expected:
514 raise SkinError("skin stream is shorter than the vertex count")
515
516 if _np is not None:
517 indices = _np.concatenate(
518 [_np.frombuffer(j0, dtype=_np.uint8).reshape(count, 4),
519 _np.frombuffer(j1, dtype=_np.uint8).reshape(count, 4)], axis=1,
520 ).astype(_np.int64)
521 weights = _np.concatenate(
522 [_np.frombuffer(w0, dtype=_np.uint8).reshape(count, 4),
523 _np.frombuffer(w1, dtype=_np.uint8).reshape(count, 4)], axis=1,
524 ).astype(_np.float64)
525 totals = weights.sum(axis=1)
526 if bool((totals <= 0).any()):
527 raise SkinError("a vertex has no skin weight")
528 if bool((weights > 0).any()):
529 weighted = indices[weights > 0]
530 if int(weighted.max()) >= local_bones:
531 raise SkinError("a weighted joint index is outside the local palette")
532 weights /= totals[:, None]
533 mapping = _np.asarray(local_to_joint, dtype=_np.uint16)
534 indices = mapping[indices]
535 indices[weights == 0] = 0
536 if joint_count is not None and bool((indices >= joint_count).any()):
537 raise SkinError("remapped joint index is invalid")
538 return {
539 "j0": indices[:, :4].astype("<u2").tobytes(),
540 "j1": indices[:, 4:].astype("<u2").tobytes(),
541 "w0": weights[:, :4].astype("<f4").tobytes(),
542 "w1": weights[:, 4:].astype("<f4").tobytes(),
543 "sum_min": float(totals.min()) / 255.0,
544 "sum_max": float(totals.max()) / 255.0,
545 }
546
547 j0_out, j1_out, w0_out, w1_out = bytearray(), bytearray(), bytearray(), bytearray()
548 sum_min, sum_max = math.inf, -math.inf
549 for vertex in range(count):
550 local = list(j0[4 * vertex:4 * vertex + 4]) + list(j1[4 * vertex:4 * vertex + 4])
551 raw = list(w0[4 * vertex:4 * vertex + 4]) + list(w1[4 * vertex:4 * vertex + 4])
552 total = sum(raw)
553 if total <= 0:
554 raise SkinError("a vertex has no skin weight")
555 sum_min, sum_max = min(sum_min, total), max(sum_max, total)
556 for slot, weight in enumerate(raw):
557 if weight and local[slot] >= local_bones:
558 raise SkinError("a weighted joint index is outside the local palette")
559 remapped = [local_to_joint[index] if raw[slot] else 0 for slot, index in enumerate(local)]
560 floats = [weight / total for weight in raw]
561 j0_out.extend(struct.pack("<4H", *remapped[:4]))
562 j1_out.extend(struct.pack("<4H", *remapped[4:]))
563 w0_out.extend(struct.pack("<4f", *floats[:4]))
564 w1_out.extend(struct.pack("<4f", *floats[4:]))
565 return {
566 "j0": bytes(j0_out), "j1": bytes(j1_out), "w0": bytes(w0_out), "w1": bytes(w1_out),
567 "sum_min": sum_min / 255.0, "sum_max": sum_max / 255.0,
568 }
569
570
571# ------------------------------------------------------------------------ glb io
572def read_glb(path: str) -> tuple[dict, bytes]:
573 """Parse a GLB container into its JSON object and BIN chunk."""
574 with open(path, "rb") as handle:
575 data = handle.read()
576 if len(data) < 20 or data[:4] != GLB_MAGIC:
577 raise SkinError(f"{path}: not a binary glTF file")
578 json_length = struct.unpack_from("<I", data, 12)[0]
579 try:
580 gltf = json.loads(data[20:20 + json_length].decode("utf-8"))
581 except (UnicodeDecodeError, json.JSONDecodeError) as exc:
582 raise SkinError(f"{path}: invalid JSON chunk: {exc}") from exc
583 offset = 20 + json_length
584 bin_data = b""
585 if offset + 8 <= len(data):
586 bin_length = struct.unpack_from("<I", data, offset)[0]
587 bin_data = data[offset + 8:offset + 8 + bin_length]
588 if not isinstance(gltf, dict):
589 raise SkinError(f"{path}: JSON root is not an object")
590 return gltf, bin_data
591
592
593def accessor_bytes(gltf: dict, bin_data: bytes, index: int) -> tuple[bytes, dict]:
594 """Return tightly packed accessor bytes and a copy of its glTF metadata."""
595 try:
596 accessor = gltf["accessors"][index]
597 view = gltf["bufferViews"][accessor["bufferView"]]
598 except (KeyError, IndexError, TypeError) as exc:
599 raise SkinError(f"invalid accessor {index}: {exc}") from exc
600 if accessor.get("sparse") is not None:
601 raise SkinError("sparse accessors are not supported")
602 component_type = accessor.get("componentType")
603 if component_type not in COMPONENT_SIZES:
604 raise SkinError(f"unsupported accessor component type {component_type!r}")
605 element = COMPONENT_SIZES[component_type] * TYPE_COMPONENTS.get(accessor.get("type"), 0)
606 count = accessor.get("count")
607 if element <= 0 or not isinstance(count, int) or count < 0:
608 raise SkinError(f"invalid accessor {index} shape")
609 stride = view.get("byteStride", element)
610 if not isinstance(stride, int) or stride < element:
611 raise SkinError(f"accessor {index} has an invalid byteStride")
612 start = view.get("byteOffset", 0) + accessor.get("byteOffset", 0)
613 end = start + stride * count
614 if start < 0 or end > len(bin_data):
615 raise SkinError(f"accessor {index} is outside the BIN chunk")
616 if stride == element:
617 packed = bin_data[start:start + element * count]
618 else:
619 packed = b"".join(bin_data[start + i * stride:start + i * stride + element]
620 for i in range(count))
621 return packed, dict(accessor)
622
623
624# -------------------------------------------------------------------- exporter
625class _GlbBuilder:
626 def __init__(self) -> None:
627 self.bin = bytearray()
628 self.views: list[dict] = []
629 self.accessors: list[dict] = []
630
631 def view(self, payload: bytes, target: int | None = None) -> int:
632 self.bin.extend(b"\x00" * ((-len(self.bin)) % 4))
633 offset = len(self.bin)
634 self.bin.extend(payload)
635 entry = {"buffer": 0, "byteOffset": offset, "byteLength": len(payload)}
636 if target is not None:
637 entry["target"] = target
638 self.views.append(entry)
639 return len(self.views) - 1
640
641 def accessor(self, payload: bytes, component_type: int, kind: str, count: int,
642 target: int | None, *, normalized: bool = False,
643 minimum: list[float] | None = None, maximum: list[float] | None = None) -> int:
644 entry = {
645 "bufferView": self.view(payload, target),
646 "componentType": component_type,
647 "count": count,
648 "type": kind,
649 }
650 if normalized:
651 entry["normalized"] = True
652 if minimum is not None:
653 entry["min"] = minimum
654 if maximum is not None:
655 entry["max"] = maximum
656 self.accessors.append(entry)
657 return len(self.accessors) - 1
658
659
660def _component_geometry(gltf: dict, bin_data: bytes, primitive: dict) -> tuple[dict, int]:
661 attributes = primitive.get("attributes")
662 if not isinstance(attributes, dict):
663 raise SkinError("source primitive has no attributes")
664 out = {}
665 for name in GEOMETRY_ATTRIBUTES:
666 if name not in attributes:
667 continue
668 payload, accessor = accessor_bytes(gltf, bin_data, attributes[name])
669 out[name] = (payload, accessor)
670 if "POSITION" not in out:
671 raise SkinError("source primitive has no POSITION accessor")
672 if "indices" not in primitive:
673 raise SkinError("source primitive has no index accessor")
674 index_payload, index_accessor = accessor_bytes(gltf, bin_data, primitive["indices"])
675 return out, (index_payload, index_accessor)
676
677
678def _source_meshes(model: dict) -> list[dict]:
679 meshes = model.get("meshes")
680 if not isinstance(meshes, list) or not meshes:
681 raise SkinError("model.json has no mesh records")
682 return meshes
683
684
685def _component_primitives(gltf: dict, wanted: int) -> list[dict]:
686 primitives = []
687 for mesh in gltf.get("meshes") or []:
688 primitives.extend(mesh.get("primitives") or [])
689 if len(primitives) != wanted:
690 raise SkinError(
691 f"model.glb has {len(primitives)} primitives for {wanted} mesh records"
692 )
693 return primitives
694
695
696def build_skinned_glb(skeleton_path: str, component_paths: list[str], *,
697 generator: str = "Leonida skinned_glb") -> tuple[bytes, dict]:
698 """Build one skinned GLB from a ped skeleton and one or more component models."""
699 _skeleton_dir, skeleton_json = model_json_path(skeleton_path)
700 ped_model = _load_json(skeleton_json)
701 ped_skeleton = (ped_model.get("drawable") or {}).get("skeleton")
702 joints = JointSet(ped_skeleton)
703
704 builder = _GlbBuilder()
705 primitives_out = []
706 records = []
707 weight_min, weight_max = math.inf, -math.inf
708
709 for component_path in component_paths:
710 model_dir, json_path = model_json_path(component_path)
711 model = _load_json(json_path)
712 source_meshes = _source_meshes(model)
713 glb_name = model.get("glb", "model.glb")
714 if not isinstance(glb_name, str) or not glb_name:
715 raise SkinError(f"{model_dir}: model.json has no model.glb name")
716 gltf, glb_bin = read_glb(os.path.join(model_dir, glb_name))
717 source_primitives = _component_primitives(gltf, len(source_meshes))
718 pairs = [(mesh, primitive) for mesh, primitive in zip(source_meshes, source_primitives)
719 if mesh.get("skinned") and mesh.get("skin_influences")]
720 if not pairs:
721 raise SkinError(f"{model_dir}: model has no skinned mesh with skin_influences")
722 resolver = PaletteResolver(model, joints.ped_by_name)
723
724 component_joint_start = joints.count
725 component_record_start = len(records)
726 for mesh, source_primitive in pairs:
727 streams = read_skin_streams(model_dir, model, mesh)
728 palette = streams["palette"]
729 if len(palette) != streams["local_bones"]:
730 raise SkinError("palette length changed while reading the skin stream")
731 local_to_joint = []
732 for value in palette:
733 name, _source = resolver.resolve(value)
734 ped_index = joints.find(name)
735 if ped_index is not None:
736 local_to_joint.append(ped_index)
737 continue
738 record = resolver.own_by_name.get(name)
739 parent_name = record.get("parent_name") if isinstance(record, dict) else None
740 if parent_name is None and isinstance(record, dict):
741 parent = record.get("parent")
742 if isinstance(parent, int) and 0 <= parent < len(resolver.own_skeleton):
743 parent_name = resolver.own_skeleton[parent].get("name")
744 parent_index = joints.find(parent_name) if isinstance(parent_name, str) else None
745 if parent_index is None:
746 inferred = infer_ped_parent(name, joints.ped_by_name)
747 parent_index = inferred if inferred is not None else joints.root
748 bind = None
749 if isinstance(record, dict) and _finite_matrix(record.get("bind_matrix")):
750 bind = bind_to_gltf(record["bind_matrix"])
751 if bind is None:
752 bind = list(joints.binds[parent_index])
753 local_to_joint.append(joints.add(name, bind, parent_index))
754
755 attributes, index_pair = _component_geometry(gltf, glb_bin, source_primitive)
756 position = attributes["POSITION"][1]
757 if position.get("count") != streams["count"]:
758 raise SkinError(
759 f"{mesh.get('name', 'mesh')}: model.glb position count "
760 f"{position.get('count')} != skin stream count {streams['count']}"
761 )
762
763 normalised = normalise_weights(
764 streams["j0"], streams["j1"], streams["w0"], streams["w1"],
765 streams["count"], streams["local_bones"], local_to_joint, joints.count,
766 )
767 weight_min = min(weight_min, normalised["sum_min"])
768 weight_max = max(weight_max, normalised["sum_max"])
769
770 gltf_attributes = {}
771 for name, (payload, accessor) in attributes.items():
772 minimum = accessor.get("min") if name == "POSITION" else None
773 maximum = accessor.get("max") if name == "POSITION" else None
774 gltf_attributes[name] = builder.accessor(
775 payload, accessor["componentType"], accessor["type"], accessor["count"],
776 ARRAY_BUFFER, normalized=bool(accessor.get("normalized")),
777 minimum=minimum, maximum=maximum,
778 )
779 index_payload, index_accessor = index_pair
780 index_count = index_accessor["count"]
781 if index_count % 3:
782 raise SkinError("source index count is not a multiple of 3")
783 gltf_attributes["JOINTS_0"] = builder.accessor(
784 normalised["j0"], COMPONENT_UNSIGNED_SHORT, "VEC4", streams["count"], ARRAY_BUFFER)
785 gltf_attributes["JOINTS_1"] = builder.accessor(
786 normalised["j1"], COMPONENT_UNSIGNED_SHORT, "VEC4", streams["count"], ARRAY_BUFFER)
787 gltf_attributes["WEIGHTS_0"] = builder.accessor(
788 normalised["w0"], COMPONENT_FLOAT, "VEC4", streams["count"], ARRAY_BUFFER)
789 gltf_attributes["WEIGHTS_1"] = builder.accessor(
790 normalised["w1"], COMPONENT_FLOAT, "VEC4", streams["count"], ARRAY_BUFFER)
791 index_accessor_index = builder.accessor(
792 index_payload, index_accessor["componentType"], index_accessor["type"],
793 index_count, ELEMENT_ARRAY_BUFFER,
794 )
795 primitives_out.append({
796 "attributes": gltf_attributes,
797 "indices": index_accessor_index,
798 "material": 0,
799 "mode": MODE_TRIANGLES,
800 })
801 records.append({
802 "component": os.path.basename(os.path.dirname(json_path)) or "component",
803 "mesh": mesh.get("name", "mesh"),
804 "vertices": streams["count"],
805 "triangles": index_count // 3,
806 "source_weight_sum_min": round(normalised["sum_min"] * 255.0, 6),
807 "source_weight_sum_max": round(normalised["sum_max"] * 255.0, 6),
808 "local_bones": streams["local_bones"],
809 })
810 component_joints = joints.count - component_joint_start
811 for record in records[component_record_start:]:
812 record["component_local_joints"] = component_joints
813
814 if joints.count > 0x10000:
815 raise SkinError("a skin may address at most 65,536 joints with UNSIGNED_SHORT indices")
816 materials = [{
817 "name": "skinned_clay",
818 "doubleSided": True,
819 "pbrMetallicRoughness": {
820 "baseColorFactor": [0.68, 0.62, 0.58, 1.0],
821 "metallicFactor": 0.0,
822 "roughnessFactor": 0.8,
823 },
824 }]
825
826 ibm_payload = b"".join(struct.pack("<16f", *joints.inverse_bind(i))
827 for i in range(joints.count))
828 ibm_accessor = builder.accessor(ibm_payload, COMPONENT_FLOAT, "MAT4", joints.count, None)
829 mesh_node = len(joints.names)
830 nodes = []
831 for index, name in enumerate(joints.names):
832 node = {"name": name}
833 local = joints.local_matrix(index)
834 if not _is_identity(local):
835 node["matrix"] = [round(v, 9) for v in local]
836 nodes.append(node)
837 nodes.append({"name": "skinned_export", "mesh": 0, "skin": 0})
838 for index, parent in enumerate(joints.parents):
839 if parent is not None:
840 nodes[parent].setdefault("children", []).append(index)
841
842 scene_nodes = [joints.root, mesh_node]
843 gltf = {
844 "asset": {"version": "2.0", "generator": generator},
845 "scene": 0,
846 "scenes": [{"name": "skinned_export", "nodes": scene_nodes}],
847 "nodes": nodes,
848 "meshes": [{"name": "skinned_export", "primitives": primitives_out}],
849 "materials": materials,
850 "accessors": builder.accessors,
851 "bufferViews": builder.views,
852 "buffers": [{"byteLength": 0}],
853 "skins": [{
854 "name": "ped_skeleton",
855 "joints": list(range(joints.count)),
856 "skeleton": joints.root,
857 "inverseBindMatrices": ibm_accessor,
858 }],
859 }
860 builder.bin.extend(b"\x00" * ((-len(builder.bin)) % 4))
861 gltf["buffers"][0]["byteLength"] = len(builder.bin)
862
863 json_bytes = json.dumps(gltf, separators=(",", ":"), ensure_ascii=False,
864 allow_nan=False).encode("utf-8")
865 json_bytes += b" " * ((-len(json_bytes)) % 4)
866 total = 12 + 8 + len(json_bytes) + 8 + len(builder.bin)
867 payload = b"".join((
868 struct.pack("<4sII", GLB_MAGIC, GLB_VERSION, total),
869 struct.pack("<II", len(json_bytes), CHUNK_JSON), json_bytes,
870 struct.pack("<II", len(builder.bin), CHUNK_BIN), bytes(builder.bin),
871 ))
872 stats = {
873 "bytes": len(payload),
874 "vertices": sum(record["vertices"] for record in records),
875 "triangles": sum(record["triangles"] for record in records),
876 "joints": joints.count,
877 "ped_joints": joints.ped_count,
878 "component_joints": joints.count - joints.ped_count,
879 "source_weight_sum_min": round(weight_min * 255.0, 6),
880 "source_weight_sum_max": round(weight_max * 255.0, 6),
881 "components": records,
882 }
883 return payload, stats
884
885
886def write_skinned_glb(path: str, skeleton_path: str, component_paths: list[str], *,
887 generator: str = "Leonida skinned_glb") -> dict:
888 """Build and atomically write a skinned GLB; returns its stats."""
889 payload, stats = build_skinned_glb(skeleton_path, component_paths, generator=generator)
890 directory = os.path.dirname(os.path.abspath(path))
891 if directory:
892 os.makedirs(directory, exist_ok=True)
893 temporary = path + ".tmp"
894 try:
895 with open(temporary, "wb") as handle:
896 handle.write(payload)
897 os.replace(temporary, path)
898 except BaseException:
899 try:
900 os.remove(temporary)
901 except OSError:
902 pass
903 raise
904 return stats
905
906
907def main(argv=None) -> int:
908 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
909 parser.add_argument("output", help="output .glb path")
910 parser.add_argument("--skeleton", required=True,
911 help="decoded ped skeleton directory or its model.json")
912 parser.add_argument("--component", action="append", required=True, metavar="DIR",
913 help="decoded component directory or its model.json (repeatable)")
914 parser.add_argument("--generator", default="Leonida skinned_glb")
915 args = parser.parse_args(argv)
916
917 try:
918 stats = write_skinned_glb(args.output, args.skeleton, args.component,
919 generator=args.generator)
920 except (SkinError, OSError) as exc:
921 print(f"error: {exc}", file=sys.stderr)
922 return 2
923 print(f"wrote {args.output}: {stats['vertices']} vertices, {stats['triangles']} triangles, "
924 f"{stats['joints']} joints ({stats['ped_joints']} ped + "
925 f"{stats['component_joints']} component)")
926 for component in stats["components"]:
927 print(f" {component['mesh']}: {component['vertices']} vertices, "
928 f"{component['local_bones']} local bones, source weight sum "
929 f"{component['source_weight_sum_min']:g}..{component['source_weight_sum_max']:g}")
930 return 0
931
932
933if __name__ == "__main__":
934 try: # a redirected stdout is strict ANSI code page under -I
935 sys.stdout.reconfigure(errors="replace")
936 except (AttributeError, ValueError, OSError):
937 pass
938 sys.exit(main())
diff --git a/tools/spirv_asm.py b/tools/spirv_asm.py
new file mode 100644
index 000000000..b485cd184
--- /dev/null
+++ b/tools/spirv_asm.py
@@ -0,0 +1,467 @@
1"""Pure-Python SPIR-V binary assembler (standard library only, no external spirv-as).
2
3Assembles SPIR-V assembly text (.spvasm) emitted by tools/rdna2spirv.py (or any
4conforming SPIR-V assembly targeting Vulkan 1.0–1.4) directly into binary SPIR-V
5words in memory.
6
7Grammar tables in tools/spirv_asm_tables.py are derived from Khronos Group
8SPIRV-Headers (MIT License): spirv.core.grammar.json and
9extinst.glsl.std.450.grammar.json.
10
11As a module:
12 from spirv_asm import assemble
13 spv_bytes = assemble(asm_text, target_env="vulkan1.2")
14
15As a CLI:
16 python3 -I tools/spirv_asm.py input.spvasm -o output.spv [--target-env vulkan1.2]
17"""
18import argparse
19import array
20import os
21import struct
22import sys
23
24_HERE = os.path.dirname(os.path.abspath(__file__))
25if _HERE not in sys.path:
26 sys.path.insert(0, _HERE)
27
28from spirv_asm_tables import BIT_ENUMS, GLSL_STD_450, INSTRUCTIONS, VALUE_ENUMS # noqa: E402
29
30SPIRV_MAGIC = 0x07230203
31
32TARGET_ENV_VERSION = {
33 "vulkan1.0": 0x00010000,
34 "vulkan1.1": 0x00010300,
35 "vulkan1.2": 0x00010500,
36 "vulkan1.3": 0x00010600,
37 "vulkan1.4": 0x00010600,
38 "spv1.0": 0x00010000,
39 "spv1.1": 0x00010100,
40 "spv1.2": 0x00010200,
41 "spv1.3": 0x00010300,
42 "spv1.4": 0x00010400,
43 "spv1.5": 0x00010500,
44 "spv1.6": 0x00010600,
45}
46
47_ID_KINDS = frozenset(("IdRef", "IdResult", "IdResultType", "IdScope", "IdMemorySemantics"))
48_EXT_SETS = {
49 "GLSL.std.450": GLSL_STD_450,
50}
51
52# Precompute fixed-arity pure-Id instructions (e.g. OpIAdd, OpFMul, OpSelect, OpStore, OpBranch)
53# so the hot loop encodes ~80% of shader lines without per-operand dispatch overhead.
54_PURE_ID_INSNS: dict[str, tuple[int, bool, bool, int, bool]] = {}
55for _opname, (_opc, _hrt, _hres, _ospecs) in INSTRUCTIONS.items():
56 if _opname in ("OpSwitch", "OpExtInst"):
57 continue
58 if all(_k in _ID_KINDS and _q in ("", "*") for _k, _q in _ospecs):
59 _has_var = bool(_ospecs and _ospecs[-1][1] == "*")
60 if not _has_var or all(_q == "" for _, _q in _ospecs[:-1]):
61 _min_args = len(_ospecs) - (1 if _has_var else 0)
62 _PURE_ID_INSNS[_opname] = (_opc, _hrt, _hres, _min_args, _has_var)
63
64
65class SpirvAsmError(ValueError):
66 """Raised when SPIR-V assembly text cannot be encoded."""
67
68
69def _tokenize_line(line: str, lineno: int) -> list[str]:
70 """Split one assembly line into tokens, stripping ';' comments outside quoted strings."""
71 if '"' not in line:
72 semi = line.find(";")
73 return (line[:semi] if semi >= 0 else line).split()
74 tokens = []
75 n = len(line)
76 i = 0
77 while i < n:
78 ch = line[i]
79 if ch <= " ":
80 i += 1
81 continue
82 if ch == ";":
83 break
84 if ch == '"':
85 j = i + 1
86 out = ['"']
87 while j < n:
88 c = line[j]
89 if c == "\\" and j + 1 < n:
90 out.append(c)
91 out.append(line[j + 1])
92 j += 2
93 elif c == '"':
94 out.append('"')
95 j += 1
96 break
97 else:
98 out.append(c)
99 j += 1
100 else:
101 raise SpirvAsmError(f"line {lineno}: unterminated string literal")
102 tokens.append("".join(out))
103 i = j
104 continue
105 j = i + 1
106 while j < n and line[j] > " " and line[j] != ";":
107 j += 1
108 tokens.append(line[i:j])
109 i = j
110 return tokens
111
112
113def _unquote_string(tok: str, lineno: int) -> str:
114 if len(tok) < 2 or tok[0] != '"' or tok[-1] != '"':
115 raise SpirvAsmError(f"line {lineno}: expected string literal, got {tok!r}")
116 raw = tok[1:-1]
117 if "\\" not in raw:
118 return raw
119 out = []
120 i = 0
121 n = len(raw)
122 while i < n:
123 if raw[i] == "\\" and i + 1 < n:
124 nxt = raw[i + 1]
125 out.append({"n": "\n", "r": "\r", "t": "\t", "\\": "\\", '"': '"'}.get(nxt, nxt))
126 i += 2
127 else:
128 out.append(raw[i])
129 i += 1
130 return "".join(out)
131
132
133def _encode_string_words(text: str) -> list[int]:
134 raw = text.encode("utf-8") + b"\x00"
135 rem = len(raw) & 3
136 if rem:
137 raw += b"\x00" * (4 - rem)
138 return list(struct.unpack(f"<{len(raw) // 4}I", raw))
139
140
141def _parse_int(tok: str, lineno: int) -> int:
142 try:
143 return int(tok, 0)
144 except ValueError as exc:
145 raise SpirvAsmError(f"line {lineno}: invalid integer literal {tok!r}") from exc
146
147
148def _parse_float(tok: str, lineno: int) -> float:
149 low = tok.lower()
150 try:
151 if ("0x" in low or "0X" in tok) and ("p" in low):
152 return float.fromhex(tok)
153 return float(tok)
154 except ValueError as exc:
155 raise SpirvAsmError(f"line {lineno}: invalid float literal {tok!r}") from exc
156
157
158def _encode_context_number(tok: str, type_info, lineno: int) -> list[int]:
159 if type_info is None:
160 raise SpirvAsmError(f"line {lineno}: OpConstant references unknown scalar type")
161 kind, width = type_info[0], type_info[1]
162 if kind == "int":
163 val = _parse_int(tok, lineno)
164 if width <= 32:
165 return [val & 0xFFFFFFFF]
166 if width == 64:
167 u64 = val & 0xFFFFFFFFFFFFFFFF
168 return [u64 & 0xFFFFFFFF, (u64 >> 32) & 0xFFFFFFFF]
169 raise SpirvAsmError(f"line {lineno}: unsupported integer constant width {width}")
170 if kind == "float":
171 fv = _parse_float(tok, lineno)
172 if width == 32:
173 return [struct.unpack("<I", struct.pack("<f", fv))[0]]
174 if width == 64:
175 return list(struct.unpack("<II", struct.pack("<d", fv)))
176 if width == 16:
177 return [struct.unpack("<H", struct.pack("<e", fv))[0]]
178 raise SpirvAsmError(f"line {lineno}: unsupported float constant width {width}")
179 raise SpirvAsmError(f"line {lineno}: unsupported constant type {type_info!r}")
180
181
182def assemble(text: str, target_env: str = "vulkan1.2") -> bytes:
183 """Assemble SPIR-V text into binary SPIR-V bytes for `target_env`."""
184 version = TARGET_ENV_VERSION.get(target_env)
185 if version is None:
186 raise SpirvAsmError(f"unsupported target environment: {target_env!r}")
187
188 sym_to_id: dict[str, int] = {}
189 next_id = 1
190 type_info: dict[int, tuple] = {} # type_id -> ('int', width, signedness) | ('float', width)
191 id_to_type: dict[int, int] = {} # result_id -> result_type_id
192 ext_imports: dict[int, dict[str, int]] = {} # ext_set_id -> {name: opcode}
193
194 def get_id(tok: str, lineno: int) -> int:
195 nonlocal next_id
196 if not tok or tok[0] != "%":
197 raise SpirvAsmError(f"line {lineno}: expected %id, got {tok!r}")
198 vid = sym_to_id.get(tok)
199 if vid is None:
200 vid = next_id
201 next_id += 1
202 sym_to_id[tok] = vid
203 return vid
204
205 words = array.array("I", [SPIRV_MAGIC, version, 0, 0, 0])
206
207 def encode_operand(kind: str, toks: list[str], idx: int, lineno: int,
208 res_type_id: int | None, cur_ext_table: dict[str, int] | None,
209 switch_width: int, out: list[int]) -> int:
210 if kind in _ID_KINDS:
211 out.append(get_id(toks[idx], lineno))
212 return idx + 1
213 if kind == "LiteralInteger":
214 out.append(_parse_int(toks[idx], lineno) & 0xFFFFFFFF)
215 return idx + 1
216 if kind == "LiteralFloat":
217 fv = _parse_float(toks[idx], lineno)
218 out.append(struct.unpack("<I", struct.pack("<f", fv))[0])
219 return idx + 1
220 if kind == "LiteralString":
221 out.extend(_encode_string_words(_unquote_string(toks[idx], lineno)))
222 return idx + 1
223 if kind == "LiteralContextDependentNumber":
224 out.extend(_encode_context_number(toks[idx], type_info.get(res_type_id), lineno))
225 return idx + 1
226 if kind == "LiteralExtInstInteger":
227 tok = toks[idx]
228 if cur_ext_table is not None and tok in cur_ext_table:
229 out.append(cur_ext_table[tok])
230 else:
231 out.append(_parse_int(tok, lineno) & 0xFFFFFFFF)
232 return idx + 1
233 if kind == "PairLiteralIntegerIdRef":
234 val = _parse_int(toks[idx], lineno)
235 if switch_width == 64:
236 u64 = val & 0xFFFFFFFFFFFFFFFF
237 out.append(u64 & 0xFFFFFFFF)
238 out.append((u64 >> 32) & 0xFFFFFFFF)
239 else:
240 out.append(val & 0xFFFFFFFF)
241 if idx + 1 >= len(toks):
242 raise SpirvAsmError(f"line {lineno}: missing label in {kind}")
243 out.append(get_id(toks[idx + 1], lineno))
244 return idx + 2
245 if kind == "PairIdRefIdRef":
246 if idx + 1 >= len(toks):
247 raise SpirvAsmError(f"line {lineno}: missing second id in {kind}")
248 out.append(get_id(toks[idx], lineno))
249 out.append(get_id(toks[idx + 1], lineno))
250 return idx + 2
251 if kind == "PairIdRefLiteralInteger":
252 if idx + 1 >= len(toks):
253 raise SpirvAsmError(f"line {lineno}: missing literal in {kind}")
254 out.append(get_id(toks[idx], lineno))
255 out.append(_parse_int(toks[idx + 1], lineno) & 0xFFFFFFFF)
256 return idx + 2
257 if kind == "LiteralSpecConstantOpInteger":
258 opname = toks[idx]
259 sub = INSTRUCTIONS.get(opname) or INSTRUCTIONS.get("Op" + opname)
260 if sub is None:
261 raise SpirvAsmError(f"line {lineno}: unknown OpSpecConstantOp opcode {opname!r}")
262 out.append(sub[0])
263 idx += 1
264 # Encode remaining operands of the nested opcode
265 for sk, sq in sub[3]:
266 if sq == "*":
267 while idx < len(toks):
268 idx = encode_operand(sk, toks, idx, lineno, res_type_id, cur_ext_table, switch_width, out)
269 elif sq == "?":
270 if idx < len(toks):
271 idx = encode_operand(sk, toks, idx, lineno, res_type_id, cur_ext_table, switch_width, out)
272 else:
273 if idx >= len(toks):
274 raise SpirvAsmError(f"line {lineno}: missing operand {sk} for {opname}")
275 idx = encode_operand(sk, toks, idx, lineno, res_type_id, cur_ext_table, switch_width, out)
276 return idx
277
278 venum = VALUE_ENUMS.get(kind)
279 if venum is not None:
280 tok = toks[idx]
281 entry = venum.get(tok)
282 if entry is None:
283 # Allow raw numeric value fallback (e.g. hex enum value)
284 if tok[:1].isdigit() or tok.startswith(("0x", "0X")):
285 out.append(_parse_int(tok, lineno) & 0xFFFFFFFF)
286 return idx + 1
287 raise SpirvAsmError(f"line {lineno}: unknown {kind} value {tok!r}")
288 val, params = entry
289 out.append(val)
290 idx += 1
291 for pk in params:
292 if idx >= len(toks):
293 raise SpirvAsmError(f"line {lineno}: missing parameter {pk} for {kind}.{tok}")
294 idx = encode_operand(pk, toks, idx, lineno, res_type_id, cur_ext_table, switch_width, out)
295 return idx
296
297 benum = BIT_ENUMS.get(kind)
298 if benum is not None:
299 tok = toks[idx]
300 mask = 0
301 flag_params: list[tuple[int, tuple[str, ...]]] = []
302 for part in tok.split("|"):
303 entry = benum.get(part)
304 if entry is None:
305 if part[:1].isdigit() or part.startswith(("0x", "0X")):
306 mask |= _parse_int(part, lineno) & 0xFFFFFFFF
307 continue
308 raise SpirvAsmError(f"line {lineno}: unknown {kind} flag {part!r} in {tok!r}")
309 bval, params = entry
310 mask |= bval
311 if params:
312 flag_params.append((bval, params))
313 out.append(mask)
314 idx += 1
315 # SPIR-V spec: bit-mask extra parameters appear in ascending bit-value order.
316 flag_params.sort(key=lambda pair: pair[0])
317 for _, params in flag_params:
318 for pk in params:
319 if idx >= len(toks):
320 raise SpirvAsmError(f"line {lineno}: missing parameter {pk} for {kind} {tok!r}")
321 idx = encode_operand(pk, toks, idx, lineno, res_type_id, cur_ext_table, switch_width, out)
322 return idx
323
324 raise SpirvAsmError(f"line {lineno}: unsupported operand kind {kind!r}")
325
326 for lineno, raw_line in enumerate(text.splitlines(), 1):
327 toks = _tokenize_line(raw_line, lineno)
328 if not toks:
329 continue
330 res_tok = None
331 if len(toks) >= 3 and toks[1] == "=":
332 res_tok = toks[0]
333 opname = toks[2]
334 arg_idx = 3
335 else:
336 opname = toks[0]
337 arg_idx = 1
338
339 fast = _PURE_ID_INSNS.get(opname)
340 if fast is not None:
341 opcode, has_rt, has_res, min_args, has_var = fast
342 if has_res != (res_tok is not None):
343 raise SpirvAsmError(
344 f"line {lineno}: {opname} "
345 + ("requires '%id =' result" if has_res else "does not produce a result id"))
346 n_rem = len(toks) - arg_idx - (1 if has_rt else 0)
347 if n_rem < min_args or (not has_var and n_rem != min_args):
348 raise SpirvAsmError(f"line {lineno}: {opname} operand count mismatch (got {n_rem})")
349 out = []
350 if has_rt:
351 rt_id = get_id(toks[arg_idx], lineno)
352 out.append(rt_id)
353 arg_idx += 1
354 else:
355 rt_id = None
356 if has_res:
357 rid = get_id(res_tok, lineno)
358 out.append(rid)
359 if rt_id is not None:
360 id_to_type[rid] = rt_id
361 for k in range(arg_idx, len(toks)):
362 out.append(get_id(toks[k], lineno))
363 word_count = 1 + len(out)
364 if word_count > 0xFFFF:
365 raise SpirvAsmError(f"line {lineno}: {opname} word count {word_count} exceeds 65535")
366 words.append((word_count << 16) | opcode)
367 words.extend(out)
368 continue
369
370 spec = INSTRUCTIONS.get(opname)
371 if spec is None:
372 raise SpirvAsmError(f"line {lineno}: unknown opcode {opname!r}")
373 opcode, has_rt, has_res, op_specs = spec
374
375 out: list[int] = []
376 res_type_id = None
377 res_id = None
378
379 if has_rt:
380 if arg_idx >= len(toks):
381 raise SpirvAsmError(f"line {lineno}: {opname} missing result type")
382 res_type_id = get_id(toks[arg_idx], lineno)
383 out.append(res_type_id)
384 arg_idx += 1
385
386 if has_res:
387 if res_tok is None:
388 raise SpirvAsmError(f"line {lineno}: {opname} requires '%id =' result")
389 res_id = get_id(res_tok, lineno)
390 out.append(res_id)
391 if res_type_id is not None:
392 id_to_type[res_id] = res_type_id
393 elif res_tok is not None:
394 raise SpirvAsmError(f"line {lineno}: {opname} does not produce a result id")
395
396 # Track scalar type widths for OpConstant / OpSwitch, and ExtInstImport sets.
397 if opname == "OpTypeInt" and res_id is not None and arg_idx + 1 < len(toks):
398 type_info[res_id] = ("int", _parse_int(toks[arg_idx], lineno), _parse_int(toks[arg_idx + 1], lineno))
399 elif opname == "OpTypeFloat" and res_id is not None and arg_idx < len(toks):
400 type_info[res_id] = ("float", _parse_int(toks[arg_idx], lineno))
401 elif opname == "OpExtInstImport" and res_id is not None and arg_idx < len(toks):
402 ext_name = _unquote_string(toks[arg_idx], lineno)
403 if ext_name in _EXT_SETS:
404 ext_imports[res_id] = _EXT_SETS[ext_name]
405
406 cur_ext_table = None
407 switch_width = 32
408 if opname == "OpExtInst" and arg_idx < len(toks):
409 cur_ext_table = ext_imports.get(get_id(toks[arg_idx], lineno))
410 elif opname == "OpSwitch" and arg_idx < len(toks):
411 sel_id = get_id(toks[arg_idx], lineno)
412 sel_ti = type_info.get(id_to_type.get(sel_id))
413 if sel_ti and sel_ti[0] == "int":
414 switch_width = sel_ti[1]
415
416 for kind, quant in op_specs:
417 if quant == "*":
418 while arg_idx < len(toks):
419 arg_idx = encode_operand(kind, toks, arg_idx, lineno, res_type_id, cur_ext_table, switch_width, out)
420 elif quant == "?":
421 if arg_idx < len(toks):
422 arg_idx = encode_operand(kind, toks, arg_idx, lineno, res_type_id, cur_ext_table, switch_width, out)
423 else:
424 if arg_idx >= len(toks):
425 raise SpirvAsmError(f"line {lineno}: {opname} missing operand ({kind})")
426 arg_idx = encode_operand(kind, toks, arg_idx, lineno, res_type_id, cur_ext_table, switch_width, out)
427
428 if arg_idx != len(toks):
429 raise SpirvAsmError(f"line {lineno}: {opname} unexpected trailing tokens {toks[arg_idx:]!r}")
430
431 word_count = 1 + len(out)
432 if word_count > 0xFFFF:
433 raise SpirvAsmError(f"line {lineno}: {opname} word count {word_count} exceeds 65535")
434 words.append((word_count << 16) | opcode)
435 words.extend(out)
436
437 words[3] = next_id
438 if sys.byteorder != "little":
439 words.byteswap()
440 return words.tobytes()
441
442
443def main(argv=None) -> int:
444 ap = argparse.ArgumentParser(description="Pure-Python SPIR-V binary assembler (no spirv-as required).")
445 ap.add_argument("src", help="input .spvasm file")
446 ap.add_argument("-o", "--out", required=True, help="output .spv binary file")
447 ap.add_argument("--target-env", default="vulkan1.2", choices=sorted(TARGET_ENV_VERSION),
448 help="target SPIR-V / Vulkan environment (default: vulkan1.2)")
449 args = ap.parse_args(argv)
450 try:
451 with open(args.src, encoding="utf-8") as f:
452 text = f.read()
453 data = assemble(text, target_env=args.target_env)
454 with open(args.out, "wb") as f:
455 f.write(data)
456 except (OSError, SpirvAsmError) as exc:
457 print(f"ERROR: {exc}", file=sys.stderr)
458 return 1
459 return 0
460
461
462if __name__ == "__main__":
463 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
464 sys.stdout.reconfigure(errors="replace")
465 except (AttributeError, ValueError, OSError):
466 pass
467 sys.exit(main())
diff --git a/tools/spirv_asm_tables.py b/tools/spirv_asm_tables.py
new file mode 100644
index 000000000..ebdecb08f
--- /dev/null
+++ b/tools/spirv_asm_tables.py
@@ -0,0 +1,1047 @@
1"""SPIR-V core and GLSL.std.450 grammar tables for tools/spirv_asm.py.
2
3Derived from Khronos Group SPIRV-Headers (MIT License):
4 spirv.core.grammar.json and extinst.glsl.std.450.grammar.json (unified1).
5"""
6
7INSTRUCTIONS = {
8 'OpAbortKHR': (5121, False, False, (('IdRef', ''), ('IdRef', ''))),
9 'OpAbsISubINTEL': (5587, True, True, (('IdRef', ''), ('IdRef', ''))),
10 'OpAbsUSubINTEL': (5588, True, True, (('IdRef', ''), ('IdRef', ''))),
11 'OpAccessChain': (65, True, True, (('IdRef', ''), ('IdRef', '*'))),
12 'OpAliasDomainDeclINTEL': (5911, False, True, ()),
13 'OpAliasScopeDeclINTEL': (5912, False, True, (('IdRef', ''),)),
14 'OpAliasScopeListDeclINTEL': (5913, False, True, (('IdRef', '*'),)),
15 'OpAll': (155, True, True, (('IdRef', ''),)),
16 'OpAllocateNodePayloadsAMDX': (5074, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))),
17 'OpAny': (154, True, True, (('IdRef', ''),)),
18 'OpArbitraryFloatACosINTEL': (5875, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
19 'OpArbitraryFloatACosPiINTEL': (5876, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
20 'OpArbitraryFloatASinINTEL': (5873, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
21 'OpArbitraryFloatASinPiINTEL': (5874, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
22 'OpArbitraryFloatATan2INTEL': (5879, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
23 'OpArbitraryFloatATanINTEL': (5877, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
24 'OpArbitraryFloatATanPiINTEL': (5878, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
25 'OpArbitraryFloatAddALTERA': (5846, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
26 'OpArbitraryFloatCastALTERA': (5841, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
27 'OpArbitraryFloatCastFromIntALTERA': (5842, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
28 'OpArbitraryFloatCastToIntALTERA': (5843, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
29 'OpArbitraryFloatCbrtALTERA': (5857, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
30 'OpArbitraryFloatCosINTEL': (5869, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
31 'OpArbitraryFloatCosPiINTEL': (5872, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
32 'OpArbitraryFloatDivALTERA': (5849, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
33 'OpArbitraryFloatEQALTERA': (5854, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''))),
34 'OpArbitraryFloatExp10INTEL': (5866, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
35 'OpArbitraryFloatExp2INTEL': (5865, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
36 'OpArbitraryFloatExpINTEL': (5864, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
37 'OpArbitraryFloatExpm1INTEL': (5867, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
38 'OpArbitraryFloatGEALTERA': (5851, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''))),
39 'OpArbitraryFloatGTALTERA': (5850, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''))),
40 'OpArbitraryFloatHypotALTERA': (5858, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
41 'OpArbitraryFloatLEALTERA': (5853, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''))),
42 'OpArbitraryFloatLTALTERA': (5852, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''))),
43 'OpArbitraryFloatLog10INTEL': (5862, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
44 'OpArbitraryFloatLog1pINTEL': (5863, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
45 'OpArbitraryFloatLog2INTEL': (5861, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
46 'OpArbitraryFloatLogINTEL': (5860, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
47 'OpArbitraryFloatMulALTERA': (5848, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
48 'OpArbitraryFloatPowINTEL': (5880, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
49 'OpArbitraryFloatPowNINTEL': (5882, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
50 'OpArbitraryFloatPowRINTEL': (5881, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
51 'OpArbitraryFloatRSqrtALTERA': (5856, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
52 'OpArbitraryFloatRecipALTERA': (5855, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
53 'OpArbitraryFloatSinCosINTEL': (5870, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
54 'OpArbitraryFloatSinCosPiALTERA': (5840, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
55 'OpArbitraryFloatSinINTEL': (5868, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
56 'OpArbitraryFloatSinPiINTEL': (5871, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
57 'OpArbitraryFloatSqrtALTERA': (5859, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
58 'OpArbitraryFloatSubALTERA': (5847, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
59 'OpArithmeticFenceEXT': (6145, True, True, (('IdRef', ''),)),
60 'OpArrayLength': (68, True, True, (('IdRef', ''), ('LiteralInteger', ''))),
61 'OpAsmCallINTEL': (5611, True, True, (('IdRef', ''), ('IdRef', '*'))),
62 'OpAsmINTEL': (5610, True, True, (('IdRef', ''), ('IdRef', ''), ('LiteralString', ''), ('LiteralString', ''))),
63 'OpAsmTargetINTEL': (5609, False, True, (('LiteralString', ''),)),
64 'OpAssumeTrueKHR': (5630, False, False, (('IdRef', ''),)),
65 'OpAtomicAnd': (240, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))),
66 'OpAtomicCompareExchange': (230, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdMemorySemantics', ''), ('IdRef', ''), ('IdRef', ''))),
67 'OpAtomicCompareExchangeWeak': (231, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdMemorySemantics', ''), ('IdRef', ''), ('IdRef', ''))),
68 'OpAtomicExchange': (229, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))),
69 'OpAtomicFAddEXT': (6035, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))),
70 'OpAtomicFMaxEXT': (5615, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))),
71 'OpAtomicFMinEXT': (5614, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))),
72 'OpAtomicFlagClear': (319, False, False, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''))),
73 'OpAtomicFlagTestAndSet': (318, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''))),
74 'OpAtomicIAdd': (234, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))),
75 'OpAtomicIDecrement': (233, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''))),
76 'OpAtomicIIncrement': (232, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''))),
77 'OpAtomicISub': (235, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))),
78 'OpAtomicLoad': (227, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''))),
79 'OpAtomicOr': (241, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))),
80 'OpAtomicSMax': (238, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))),
81 'OpAtomicSMin': (236, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))),
82 'OpAtomicStore': (228, False, False, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))),
83 'OpAtomicUMax': (239, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))),
84 'OpAtomicUMin': (237, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))),
85 'OpAtomicXor': (242, True, True, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''), ('IdRef', ''))),
86 'OpBFloat16MulAddQCOM': (4505, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
87 'OpBeginInvocationInterlockEXT': (5364, False, False, ()),
88 'OpBitCastArrayQCOM': (4497, True, True, (('IdRef', ''),)),
89 'OpBitCount': (205, True, True, (('IdRef', ''),)),
90 'OpBitFieldInsert': (201, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
91 'OpBitFieldSExtract': (202, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
92 'OpBitFieldUExtract': (203, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
93 'OpBitReverse': (204, True, True, (('IdRef', ''),)),
94 'OpBitcast': (124, True, True, (('IdRef', ''),)),
95 'OpBitcastExtractEXT': (4195, True, True, (('IdRef', ''), ('IdRef', ''))),
96 'OpBitwiseAnd': (199, True, True, (('IdRef', ''), ('IdRef', ''))),
97 'OpBitwiseFunctionINTEL': (6242, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
98 'OpBitwiseOr': (197, True, True, (('IdRef', ''), ('IdRef', ''))),
99 'OpBitwiseXor': (198, True, True, (('IdRef', ''), ('IdRef', ''))),
100 'OpBranch': (249, False, False, (('IdRef', ''),)),
101 'OpBranchConditional': (250, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('LiteralInteger', '*'))),
102 'OpBufferPointerEXT': (5119, True, True, (('IdRef', ''),)),
103 'OpBuildNDRange': (304, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
104 'OpCapability': (17, False, False, (('Capability', ''),)),
105 'OpCaptureEventProfilingInfo': (302, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
106 'OpClampConvertFToSINTEL': (6424, True, True, (('IdRef', ''),)),
107 'OpClampStochasticRoundFToSINTEL': (6219, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '?'))),
108 'OpColorAttachmentReadEXT': (4160, True, True, (('IdRef', ''), ('IdRef', '?'))),
109 'OpCommitReadPipe': (280, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
110 'OpCommitWritePipe': (281, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
111 'OpCompositeConstruct': (80, True, True, (('IdRef', '*'),)),
112 'OpCompositeConstructContinuedINTEL': (6096, False, False, (('IdRef', '*'),)),
113 'OpCompositeConstructCoopMatQCOM': (4540, True, True, (('IdRef', ''),)),
114 'OpCompositeConstructReplicateEXT': (4463, True, True, (('IdRef', ''),)),
115 'OpCompositeExtract': (81, True, True, (('IdRef', ''), ('LiteralInteger', '*'))),
116 'OpCompositeExtractCoopMatQCOM': (4541, True, True, (('IdRef', ''),)),
117 'OpCompositeInsert': (82, True, True, (('IdRef', ''), ('IdRef', ''), ('LiteralInteger', '*'))),
118 'OpConditionalCapabilityINTEL': (6250, False, False, (('IdRef', ''), ('Capability', ''))),
119 'OpConditionalCopyObjectINTEL': (6254, True, True, (('IdRef', '*'),)),
120 'OpConditionalEntryPointINTEL': (6249, False, False, (('IdRef', ''), ('ExecutionModel', ''), ('IdRef', ''), ('LiteralString', ''), ('IdRef', '*'))),
121 'OpConditionalExtensionINTEL': (6248, False, False, (('IdRef', ''), ('LiteralString', ''))),
122 'OpConstant': (43, True, True, (('LiteralContextDependentNumber', ''),)),
123 'OpConstantComposite': (44, True, True, (('IdRef', '*'),)),
124 'OpConstantCompositeContinuedINTEL': (6091, False, False, (('IdRef', '*'),)),
125 'OpConstantCompositeReplicateEXT': (4461, True, True, (('IdRef', ''),)),
126 'OpConstantDataKHR': (5147, True, True, (('LiteralInteger', '*'),)),
127 'OpConstantFalse': (42, True, True, ()),
128 'OpConstantFunctionPointerINTEL': (5600, True, True, (('IdRef', ''),)),
129 'OpConstantNull': (46, True, True, ()),
130 'OpConstantPipeStorage': (323, True, True, (('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
131 'OpConstantSampler': (45, True, True, (('SamplerAddressingMode', ''), ('LiteralInteger', ''), ('SamplerFilterMode', ''))),
132 'OpConstantSizeOfEXT': (5129, True, True, (('IdRef', ''),)),
133 'OpConstantStringAMDX': (5103, False, True, (('LiteralString', ''),)),
134 'OpConstantTrue': (41, True, True, ()),
135 'OpControlBarrier': (224, False, False, (('IdScope', ''), ('IdScope', ''), ('IdMemorySemantics', ''))),
136 'OpControlBarrierArriveEXT': (6142, False, False, (('IdScope', ''), ('IdScope', ''), ('IdMemorySemantics', ''))),
137 'OpControlBarrierWaitEXT': (6143, False, False, (('IdScope', ''), ('IdScope', ''), ('IdMemorySemantics', ''))),
138 'OpConvertBF16ToFINTEL': (6117, True, True, (('IdRef', ''),)),
139 'OpConvertFToBF16INTEL': (6116, True, True, (('IdRef', ''),)),
140 'OpConvertFToS': (110, True, True, (('IdRef', ''),)),
141 'OpConvertFToU': (109, True, True, (('IdRef', ''),)),
142 'OpConvertHandleToImageINTEL': (6529, True, True, (('IdRef', ''),)),
143 'OpConvertHandleToSampledImageINTEL': (6531, True, True, (('IdRef', ''),)),
144 'OpConvertHandleToSamplerINTEL': (6530, True, True, (('IdRef', ''),)),
145 'OpConvertImageToUNV': (5393, True, True, (('IdRef', ''),)),
146 'OpConvertPtrToU': (117, True, True, (('IdRef', ''),)),
147 'OpConvertSToF': (111, True, True, (('IdRef', ''),)),
148 'OpConvertSampledImageToUNV': (5396, True, True, (('IdRef', ''),)),
149 'OpConvertSamplerToUNV': (5394, True, True, (('IdRef', ''),)),
150 'OpConvertUToAccelerationStructureKHR': (4447, True, True, (('IdRef', ''),)),
151 'OpConvertUToF': (112, True, True, (('IdRef', ''),)),
152 'OpConvertUToImageNV': (5391, True, True, (('IdRef', ''),)),
153 'OpConvertUToPtr': (120, True, True, (('IdRef', ''),)),
154 'OpConvertUToSampledImageNV': (5395, True, True, (('IdRef', ''),)),
155 'OpConvertUToSamplerNV': (5392, True, True, (('IdRef', ''),)),
156 'OpCooperativeMatrixConvertUseEXT': (5293, True, True, (('IdRef', ''),)),
157 'OpCooperativeMatrixGetCoordinateEXT': (5363, True, True, (('IdRef', ''), ('IdRef', ''))),
158 'OpCooperativeMatrixLengthKHR': (4460, True, True, (('IdRef', ''),)),
159 'OpCooperativeMatrixLengthNV': (5362, True, True, (('IdRef', ''),)),
160 'OpCooperativeMatrixLoadKHR': (4457, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('MemoryAccess', '?'))),
161 'OpCooperativeMatrixLoadNV': (5359, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))),
162 'OpCooperativeMatrixLoadTensorNV': (5367, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', ''), ('TensorAddressingOperands', ''))),
163 'OpCooperativeMatrixMulAddKHR': (4459, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('CooperativeMatrixOperands', '?'))),
164 'OpCooperativeMatrixMulAddNV': (5361, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
165 'OpCooperativeMatrixPerElementOpEXT': (5369, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))),
166 'OpCooperativeMatrixReduceEXT': (5366, True, True, (('IdRef', ''), ('CooperativeMatrixReduce', ''), ('IdRef', ''))),
167 'OpCooperativeMatrixStoreKHR': (4458, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('MemoryAccess', '?'))),
168 'OpCooperativeMatrixStoreNV': (5360, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))),
169 'OpCooperativeMatrixStoreTensorNV': (5368, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', ''), ('TensorAddressingOperands', ''))),
170 'OpCooperativeMatrixTransposeNV': (5390, True, True, (('IdRef', ''),)),
171 'OpCooperativeVectorLoadNV': (5302, True, True, (('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))),
172 'OpCooperativeVectorMatrixMulAddNV': (5292, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('CooperativeMatrixOperands', '?'))),
173 'OpCooperativeVectorMatrixMulNV': (5289, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('CooperativeMatrixOperands', '?'))),
174 'OpCooperativeVectorOuterProductAccumulateNV': (5290, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'))),
175 'OpCooperativeVectorReduceSumAccumulateNV': (5291, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
176 'OpCooperativeVectorStoreNV': (5303, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))),
177 'OpCopyLogical': (400, True, True, (('IdRef', ''),)),
178 'OpCopyMemory': (63, False, False, (('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'), ('MemoryAccess', '?'))),
179 'OpCopyMemorySized': (64, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'), ('MemoryAccess', '?'))),
180 'OpCopyObject': (83, True, True, (('IdRef', ''),)),
181 'OpCreatePipeFromPipeStorage': (324, True, True, (('IdRef', ''),)),
182 'OpCreateTensorLayoutNV': (5372, True, True, ()),
183 'OpCreateTensorViewNV': (5377, True, True, ()),
184 'OpCreateUserEvent': (299, True, True, ()),
185 'OpCrossWorkgroupCastToPtrALTERA': (5938, True, True, (('IdRef', ''),)),
186 'OpDPdx': (207, True, True, (('IdRef', ''),)),
187 'OpDPdxCoarse': (213, True, True, (('IdRef', ''),)),
188 'OpDPdxFine': (210, True, True, (('IdRef', ''),)),
189 'OpDPdy': (208, True, True, (('IdRef', ''),)),
190 'OpDPdyCoarse': (214, True, True, (('IdRef', ''),)),
191 'OpDPdyFine': (211, True, True, (('IdRef', ''),)),
192 'OpDecorate': (71, False, False, (('IdRef', ''), ('Decoration', ''))),
193 'OpDecorateId': (332, False, False, (('IdRef', ''), ('Decoration', ''))),
194 'OpDecorateString': (5632, False, False, (('IdRef', ''), ('Decoration', ''))),
195 'OpDecorationGroup': (73, False, True, ()),
196 'OpDemoteToHelperInvocation': (5380, False, False, ()),
197 'OpDepthAttachmentReadEXT': (4161, True, True, (('IdRef', '?'),)),
198 'OpDot': (148, True, True, (('IdRef', ''), ('IdRef', ''))),
199 'OpEmitMeshTasksEXT': (5294, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'))),
200 'OpEmitStreamVertex': (220, False, False, (('IdRef', ''),)),
201 'OpEmitVertex': (218, False, False, ()),
202 'OpEndInvocationInterlockEXT': (5365, False, False, ()),
203 'OpEndPrimitive': (219, False, False, ()),
204 'OpEndStreamPrimitive': (221, False, False, (('IdRef', ''),)),
205 'OpEnqueueKernel': (292, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))),
206 'OpEnqueueMarker': (291, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
207 'OpEnqueueNodePayloadsAMDX': (5075, False, False, (('IdRef', ''),)),
208 'OpEntryPoint': (15, False, False, (('ExecutionModel', ''), ('IdRef', ''), ('LiteralString', ''), ('IdRef', '*'))),
209 'OpExecuteCallableKHR': (4446, False, False, (('IdRef', ''), ('IdRef', ''))),
210 'OpExecuteCallableNV': (5344, False, False, (('IdRef', ''), ('IdRef', ''))),
211 'OpExecutionMode': (16, False, False, (('IdRef', ''), ('ExecutionMode', ''))),
212 'OpExecutionModeId': (331, False, False, (('IdRef', ''), ('ExecutionMode', ''))),
213 'OpExpectKHR': (5631, True, True, (('IdRef', ''), ('IdRef', ''))),
214 'OpExtInst': (12, True, True, (('IdRef', ''), ('LiteralExtInstInteger', ''), ('IdRef', '*'))),
215 'OpExtInstImport': (11, False, True, (('LiteralString', ''),)),
216 'OpExtInstWithForwardRefsKHR': (4433, True, True, (('IdRef', ''), ('LiteralExtInstInteger', ''), ('IdRef', '*'))),
217 'OpExtension': (10, False, False, (('LiteralString', ''),)),
218 'OpExtractSubArrayQCOM': (4542, True, True, (('IdRef', ''), ('IdRef', ''))),
219 'OpFAdd': (129, True, True, (('IdRef', ''), ('IdRef', ''))),
220 'OpFConvert': (115, True, True, (('IdRef', ''),)),
221 'OpFDiv': (136, True, True, (('IdRef', ''), ('IdRef', ''))),
222 'OpFDot2MixAcc16VALVE': (6917, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
223 'OpFDot2MixAcc32VALVE': (6916, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
224 'OpFDot4MixAcc32VALVE': (6918, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
225 'OpFMod': (141, True, True, (('IdRef', ''), ('IdRef', ''))),
226 'OpFMul': (133, True, True, (('IdRef', ''), ('IdRef', ''))),
227 'OpFNegate': (127, True, True, (('IdRef', ''),)),
228 'OpFOrdEqual': (180, True, True, (('IdRef', ''), ('IdRef', ''))),
229 'OpFOrdGreaterThan': (186, True, True, (('IdRef', ''), ('IdRef', ''))),
230 'OpFOrdGreaterThanEqual': (190, True, True, (('IdRef', ''), ('IdRef', ''))),
231 'OpFOrdLessThan': (184, True, True, (('IdRef', ''), ('IdRef', ''))),
232 'OpFOrdLessThanEqual': (188, True, True, (('IdRef', ''), ('IdRef', ''))),
233 'OpFOrdNotEqual': (182, True, True, (('IdRef', ''), ('IdRef', ''))),
234 'OpFPGARegALTERA': (5949, True, True, (('IdRef', ''),)),
235 'OpFRem': (140, True, True, (('IdRef', ''), ('IdRef', ''))),
236 'OpFSub': (131, True, True, (('IdRef', ''), ('IdRef', ''))),
237 'OpFUnordEqual': (181, True, True, (('IdRef', ''), ('IdRef', ''))),
238 'OpFUnordGreaterThan': (187, True, True, (('IdRef', ''), ('IdRef', ''))),
239 'OpFUnordGreaterThanEqual': (191, True, True, (('IdRef', ''), ('IdRef', ''))),
240 'OpFUnordLessThan': (185, True, True, (('IdRef', ''), ('IdRef', ''))),
241 'OpFUnordLessThanEqual': (189, True, True, (('IdRef', ''), ('IdRef', ''))),
242 'OpFUnordNotEqual': (183, True, True, (('IdRef', ''), ('IdRef', ''))),
243 'OpFetchMicroTriangleVertexBarycentricNV': (5301, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
244 'OpFetchMicroTriangleVertexPositionNV': (5300, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
245 'OpFinishWritingNodePayloadAMDX': (5078, True, True, (('IdRef', ''),)),
246 'OpFixedCosALTERA': (5927, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
247 'OpFixedCosPiALTERA': (5930, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
248 'OpFixedExpALTERA': (5933, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
249 'OpFixedLogALTERA': (5932, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
250 'OpFixedRecipALTERA': (5924, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
251 'OpFixedRsqrtALTERA': (5925, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
252 'OpFixedSinALTERA': (5926, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
253 'OpFixedSinCosALTERA': (5928, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
254 'OpFixedSinCosPiALTERA': (5931, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
255 'OpFixedSinPiALTERA': (5929, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
256 'OpFixedSqrtALTERA': (5923, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
257 'OpFmaKHR': (4427, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
258 'OpFragmentFetchAMD': (5012, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
259 'OpFragmentMaskFetchAMD': (5011, True, True, (('IdRef', ''), ('IdRef', ''))),
260 'OpFreezeKHR': (5159, True, True, (('IdRef', ''),)),
261 'OpFunction': (54, True, True, (('FunctionControl', ''), ('IdRef', ''))),
262 'OpFunctionCall': (57, True, True, (('IdRef', ''), ('IdRef', '*'))),
263 'OpFunctionEnd': (56, False, False, ()),
264 'OpFunctionParameter': (55, True, True, ()),
265 'OpFunctionPointerCallINTEL': (5601, True, True, (('IdRef', '*'),)),
266 'OpFwidth': (209, True, True, (('IdRef', ''),)),
267 'OpFwidthCoarse': (215, True, True, (('IdRef', ''),)),
268 'OpFwidthFine': (212, True, True, (('IdRef', ''),)),
269 'OpGenericCastToPtr': (122, True, True, (('IdRef', ''),)),
270 'OpGenericCastToPtrExplicit': (123, True, True, (('IdRef', ''), ('StorageClass', ''))),
271 'OpGenericPtrMemSemantics': (69, True, True, (('IdRef', ''),)),
272 'OpGetDefaultQueue': (303, True, True, ()),
273 'OpGetInstanceCustomIndexAtLevelAMDX': (5193, True, True, (('IdRef', ''),)),
274 'OpGetInstanceIdAtLevelAMDX': (5194, True, True, (('IdRef', ''),)),
275 'OpGetKernelLocalSizeForSubgroupCount': (325, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
276 'OpGetKernelMaxNumSubgroups': (326, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
277 'OpGetKernelNDrangeMaxSubGroupSize': (294, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
278 'OpGetKernelNDrangeSubGroupCount': (293, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
279 'OpGetKernelPreferredWorkGroupSizeMultiple': (296, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
280 'OpGetKernelWorkGroupSize': (295, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
281 'OpGetMaxPipePackets': (284, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
282 'OpGetNumPipePackets': (283, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
283 'OpGetObjectToWorldAtLevelAMDX': (5195, True, True, (('IdRef', ''),)),
284 'OpGetWorldToObjectAtLevelAMDX': (5196, True, True, (('IdRef', ''),)),
285 'OpGraphARM': (4183, True, True, ()),
286 'OpGraphConstantARM': (4181, True, True, (('LiteralInteger', ''),)),
287 'OpGraphEndARM': (4186, False, False, ()),
288 'OpGraphEntryPointARM': (4182, False, False, (('IdRef', ''), ('LiteralString', ''), ('IdRef', '*'))),
289 'OpGraphInputARM': (4184, True, True, (('IdRef', ''), ('IdRef', '*'))),
290 'OpGraphSetOutputARM': (4185, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))),
291 'OpGroupAll': (261, True, True, (('IdScope', ''), ('IdRef', ''))),
292 'OpGroupAny': (262, True, True, (('IdScope', ''), ('IdRef', ''))),
293 'OpGroupAsyncCopy': (259, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
294 'OpGroupBitwiseAndKHR': (6403, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
295 'OpGroupBitwiseOrKHR': (6404, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
296 'OpGroupBitwiseXorKHR': (6405, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
297 'OpGroupBroadcast': (263, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))),
298 'OpGroupCommitReadPipe': (287, False, False, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
299 'OpGroupCommitWritePipe': (288, False, False, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
300 'OpGroupDecorate': (74, False, False, (('IdRef', ''), ('IdRef', '*'))),
301 'OpGroupFAdd': (265, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
302 'OpGroupFAddNonUniformAMD': (5001, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
303 'OpGroupFMax': (269, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
304 'OpGroupFMaxNonUniformAMD': (5005, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
305 'OpGroupFMin': (266, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
306 'OpGroupFMinNonUniformAMD': (5002, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
307 'OpGroupFMulKHR': (6402, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
308 'OpGroupIAdd': (264, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
309 'OpGroupIAddNonUniformAMD': (5000, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
310 'OpGroupIMulKHR': (6401, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
311 'OpGroupLogicalAndKHR': (6406, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
312 'OpGroupLogicalOrKHR': (6407, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
313 'OpGroupLogicalXorKHR': (6408, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
314 'OpGroupMemberDecorate': (75, False, False, (('IdRef', ''), ('PairIdRefLiteralInteger', '*'))),
315 'OpGroupNonUniformAll': (334, True, True, (('IdScope', ''), ('IdRef', ''))),
316 'OpGroupNonUniformAllEqual': (336, True, True, (('IdScope', ''), ('IdRef', ''))),
317 'OpGroupNonUniformAny': (335, True, True, (('IdScope', ''), ('IdRef', ''))),
318 'OpGroupNonUniformBallot': (339, True, True, (('IdScope', ''), ('IdRef', ''))),
319 'OpGroupNonUniformBallotBitCount': (342, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
320 'OpGroupNonUniformBallotBitExtract': (341, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))),
321 'OpGroupNonUniformBallotFindLSB': (343, True, True, (('IdScope', ''), ('IdRef', ''))),
322 'OpGroupNonUniformBallotFindMSB': (344, True, True, (('IdScope', ''), ('IdRef', ''))),
323 'OpGroupNonUniformBitwiseAnd': (359, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
324 'OpGroupNonUniformBitwiseOr': (360, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
325 'OpGroupNonUniformBitwiseXor': (361, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
326 'OpGroupNonUniformBroadcast': (337, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))),
327 'OpGroupNonUniformBroadcastFirst': (338, True, True, (('IdScope', ''), ('IdRef', ''))),
328 'OpGroupNonUniformElect': (333, True, True, (('IdScope', ''),)),
329 'OpGroupNonUniformFAdd': (350, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
330 'OpGroupNonUniformFMax': (358, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
331 'OpGroupNonUniformFMin': (355, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
332 'OpGroupNonUniformFMul': (352, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
333 'OpGroupNonUniformIAdd': (349, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
334 'OpGroupNonUniformIMul': (351, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
335 'OpGroupNonUniformInverseBallot': (340, True, True, (('IdScope', ''), ('IdRef', ''))),
336 'OpGroupNonUniformLogicalAnd': (362, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
337 'OpGroupNonUniformLogicalOr': (363, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
338 'OpGroupNonUniformLogicalXor': (364, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
339 'OpGroupNonUniformPartitionEXT': (5296, True, True, (('IdRef', ''),)),
340 'OpGroupNonUniformQuadAllKHR': (5110, True, True, (('IdRef', ''),)),
341 'OpGroupNonUniformQuadAnyKHR': (5111, True, True, (('IdRef', ''),)),
342 'OpGroupNonUniformQuadBroadcast': (365, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))),
343 'OpGroupNonUniformQuadSwap': (366, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))),
344 'OpGroupNonUniformRotateKHR': (4431, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'))),
345 'OpGroupNonUniformSMax': (356, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
346 'OpGroupNonUniformSMin': (353, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
347 'OpGroupNonUniformShuffle': (345, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))),
348 'OpGroupNonUniformShuffleDown': (348, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))),
349 'OpGroupNonUniformShuffleUp': (347, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))),
350 'OpGroupNonUniformShuffleXor': (346, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))),
351 'OpGroupNonUniformUMax': (357, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
352 'OpGroupNonUniformUMin': (354, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''), ('IdRef', '?'))),
353 'OpGroupReserveReadPipePackets': (285, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
354 'OpGroupReserveWritePipePackets': (286, True, True, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
355 'OpGroupSMax': (271, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
356 'OpGroupSMaxNonUniformAMD': (5007, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
357 'OpGroupSMin': (268, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
358 'OpGroupSMinNonUniformAMD': (5004, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
359 'OpGroupUMax': (270, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
360 'OpGroupUMaxNonUniformAMD': (5006, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
361 'OpGroupUMin': (267, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
362 'OpGroupUMinNonUniformAMD': (5003, True, True, (('IdScope', ''), ('GroupOperation', ''), ('IdRef', ''))),
363 'OpGroupWaitEvents': (260, False, False, (('IdScope', ''), ('IdRef', ''), ('IdRef', ''))),
364 'OpHitObjectExecuteShaderEXT': (5319, False, False, (('IdRef', ''), ('IdRef', ''))),
365 'OpHitObjectExecuteShaderNV': (5264, False, False, (('IdRef', ''), ('IdRef', ''))),
366 'OpHitObjectGetAttributesEXT': (5321, False, False, (('IdRef', ''), ('IdRef', ''))),
367 'OpHitObjectGetAttributesNV': (5266, False, False, (('IdRef', ''), ('IdRef', ''))),
368 'OpHitObjectGetClusterIdNV': (5346, True, True, (('IdRef', ''),)),
369 'OpHitObjectGetCurrentTimeEXT': (5320, True, True, (('IdRef', ''),)),
370 'OpHitObjectGetCurrentTimeNV': (5265, True, True, (('IdRef', ''),)),
371 'OpHitObjectGetGeometryIndexEXT': (5324, True, True, (('IdRef', ''),)),
372 'OpHitObjectGetGeometryIndexNV': (5269, True, True, (('IdRef', ''),)),
373 'OpHitObjectGetHitKindEXT': (5322, True, True, (('IdRef', ''),)),
374 'OpHitObjectGetHitKindNV': (5267, True, True, (('IdRef', ''),)),
375 'OpHitObjectGetInstanceCustomIndexEXT': (5326, True, True, (('IdRef', ''),)),
376 'OpHitObjectGetInstanceCustomIndexNV': (5271, True, True, (('IdRef', ''),)),
377 'OpHitObjectGetInstanceIdEXT': (5325, True, True, (('IdRef', ''),)),
378 'OpHitObjectGetInstanceIdNV': (5270, True, True, (('IdRef', ''),)),
379 'OpHitObjectGetIntersectionTriangleVertexPositionsEXT': (5307, True, True, (('IdRef', ''),)),
380 'OpHitObjectGetLSSPositionsNV': (5434, True, True, (('IdRef', ''),)),
381 'OpHitObjectGetLSSRadiiNV': (5435, True, True, (('IdRef', ''),)),
382 'OpHitObjectGetObjectRayDirectionEXT': (5328, True, True, (('IdRef', ''),)),
383 'OpHitObjectGetObjectRayDirectionNV': (5254, True, True, (('IdRef', ''),)),
384 'OpHitObjectGetObjectRayOriginEXT': (5327, True, True, (('IdRef', ''),)),
385 'OpHitObjectGetObjectRayOriginNV': (5255, True, True, (('IdRef', ''),)),
386 'OpHitObjectGetObjectToWorldEXT': (5331, True, True, (('IdRef', ''),)),
387 'OpHitObjectGetObjectToWorldNV': (5253, True, True, (('IdRef', ''),)),
388 'OpHitObjectGetPrimitiveIndexEXT': (5323, True, True, (('IdRef', ''),)),
389 'OpHitObjectGetPrimitiveIndexNV': (5268, True, True, (('IdRef', ''),)),
390 'OpHitObjectGetRayFlagsEXT': (5308, True, True, (('IdRef', ''),)),
391 'OpHitObjectGetRayTMaxEXT': (5333, True, True, (('IdRef', ''),)),
392 'OpHitObjectGetRayTMaxNV': (5274, True, True, (('IdRef', ''),)),
393 'OpHitObjectGetRayTMinEXT': (5347, True, True, (('IdRef', ''),)),
394 'OpHitObjectGetRayTMinNV': (5275, True, True, (('IdRef', ''),)),
395 'OpHitObjectGetShaderBindingTableRecordIndexEXT': (5348, True, True, (('IdRef', ''),)),
396 'OpHitObjectGetShaderBindingTableRecordIndexNV': (5258, True, True, (('IdRef', ''),)),
397 'OpHitObjectGetShaderRecordBufferHandleEXT': (5349, True, True, (('IdRef', ''),)),
398 'OpHitObjectGetShaderRecordBufferHandleNV': (5257, True, True, (('IdRef', ''),)),
399 'OpHitObjectGetSpherePositionNV': (5432, True, True, (('IdRef', ''),)),
400 'OpHitObjectGetSphereRadiusNV': (5433, True, True, (('IdRef', ''),)),
401 'OpHitObjectGetWorldRayDirectionEXT': (5329, True, True, (('IdRef', ''),)),
402 'OpHitObjectGetWorldRayDirectionNV': (5272, True, True, (('IdRef', ''),)),
403 'OpHitObjectGetWorldRayOriginEXT': (5330, True, True, (('IdRef', ''),)),
404 'OpHitObjectGetWorldRayOriginNV': (5273, True, True, (('IdRef', ''),)),
405 'OpHitObjectGetWorldToObjectEXT': (5332, True, True, (('IdRef', ''),)),
406 'OpHitObjectGetWorldToObjectNV': (5252, True, True, (('IdRef', ''),)),
407 'OpHitObjectIsEmptyEXT': (5350, True, True, (('IdRef', ''),)),
408 'OpHitObjectIsEmptyNV': (5276, True, True, (('IdRef', ''),)),
409 'OpHitObjectIsHitEXT': (5351, True, True, (('IdRef', ''),)),
410 'OpHitObjectIsHitNV': (5277, True, True, (('IdRef', ''),)),
411 'OpHitObjectIsLSSHitNV': (5437, True, True, (('IdRef', ''),)),
412 'OpHitObjectIsMissEXT': (5352, True, True, (('IdRef', ''),)),
413 'OpHitObjectIsMissNV': (5278, True, True, (('IdRef', ''),)),
414 'OpHitObjectIsSphereHitNV': (5436, True, True, (('IdRef', ''),)),
415 'OpHitObjectRecordEmptyEXT': (5318, False, False, (('IdRef', ''),)),
416 'OpHitObjectRecordEmptyNV': (5259, False, False, (('IdRef', ''),)),
417 'OpHitObjectRecordFromQueryEXT': (5304, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'))),
418 'OpHitObjectRecordHitMotionNV': (5249, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
419 'OpHitObjectRecordHitNV': (5261, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
420 'OpHitObjectRecordHitWithIndexMotionNV': (5250, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
421 'OpHitObjectRecordHitWithIndexNV': (5262, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
422 'OpHitObjectRecordMissEXT': (5305, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
423 'OpHitObjectRecordMissMotionEXT': (5306, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
424 'OpHitObjectRecordMissMotionNV': (5251, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
425 'OpHitObjectRecordMissNV': (5263, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
426 'OpHitObjectReorderExecuteShaderEXT': (5310, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('IdRef', '?'))),
427 'OpHitObjectSetShaderBindingTableRecordIndexEXT': (5309, False, False, (('IdRef', ''), ('IdRef', ''))),
428 'OpHitObjectTraceMotionReorderExecuteEXT': (5312, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('IdRef', '?'))),
429 'OpHitObjectTraceRayEXT': (5316, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
430 'OpHitObjectTraceRayMotionEXT': (5317, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
431 'OpHitObjectTraceRayMotionNV': (5256, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
432 'OpHitObjectTraceRayNV': (5260, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
433 'OpHitObjectTraceReorderExecuteEXT': (5311, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('IdRef', '?'))),
434 'OpIAdd': (128, True, True, (('IdRef', ''), ('IdRef', ''))),
435 'OpIAddCarry': (149, True, True, (('IdRef', ''), ('IdRef', ''))),
436 'OpIAddSatINTEL': (5589, True, True, (('IdRef', ''), ('IdRef', ''))),
437 'OpIAverageINTEL': (5591, True, True, (('IdRef', ''), ('IdRef', ''))),
438 'OpIAverageRoundedINTEL': (5593, True, True, (('IdRef', ''), ('IdRef', ''))),
439 'OpIEqual': (170, True, True, (('IdRef', ''), ('IdRef', ''))),
440 'OpIMul': (132, True, True, (('IdRef', ''), ('IdRef', ''))),
441 'OpIMul32x16INTEL': (5597, True, True, (('IdRef', ''), ('IdRef', ''))),
442 'OpINotEqual': (171, True, True, (('IdRef', ''), ('IdRef', ''))),
443 'OpISub': (130, True, True, (('IdRef', ''), ('IdRef', ''))),
444 'OpISubBorrow': (150, True, True, (('IdRef', ''), ('IdRef', ''))),
445 'OpISubSatINTEL': (5595, True, True, (('IdRef', ''), ('IdRef', ''))),
446 'OpIgnoreIntersectionKHR': (4448, False, False, ()),
447 'OpIgnoreIntersectionNV': (5335, False, False, ()),
448 'OpImage': (100, True, True, (('IdRef', ''),)),
449 'OpImageBlockMatchGatherSADQCOM': (4503, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
450 'OpImageBlockMatchGatherSSDQCOM': (4502, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
451 'OpImageBlockMatchSADQCOM': (4483, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
452 'OpImageBlockMatchSSDQCOM': (4482, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
453 'OpImageBlockMatchWindowSADQCOM': (4501, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
454 'OpImageBlockMatchWindowSSDQCOM': (4500, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
455 'OpImageBoxFilterQCOM': (4481, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
456 'OpImageDrefGather': (97, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
457 'OpImageFetch': (95, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
458 'OpImageGather': (96, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
459 'OpImageGatherQCOM': (4545, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
460 'OpImageQueryFormat': (101, True, True, (('IdRef', ''),)),
461 'OpImageQueryLevels': (106, True, True, (('IdRef', ''),)),
462 'OpImageQueryLod': (105, True, True, (('IdRef', ''), ('IdRef', ''))),
463 'OpImageQueryOrder': (102, True, True, (('IdRef', ''),)),
464 'OpImageQuerySamples': (107, True, True, (('IdRef', ''),)),
465 'OpImageQuerySize': (104, True, True, (('IdRef', ''),)),
466 'OpImageQuerySizeLod': (103, True, True, (('IdRef', ''), ('IdRef', ''))),
467 'OpImageRead': (98, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
468 'OpImageSampleDrefExplicitLod': (90, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))),
469 'OpImageSampleDrefImplicitLod': (89, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
470 'OpImageSampleExplicitLod': (88, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))),
471 'OpImageSampleFootprintNV': (5283, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
472 'OpImageSampleImplicitLod': (87, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
473 'OpImageSampleProjDrefExplicitLod': (94, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))),
474 'OpImageSampleProjDrefImplicitLod': (93, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
475 'OpImageSampleProjExplicitLod': (92, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))),
476 'OpImageSampleProjImplicitLod': (91, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
477 'OpImageSampleWeightedQCOM': (4480, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
478 'OpImageSparseDrefGather': (315, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
479 'OpImageSparseFetch': (313, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
480 'OpImageSparseGather': (314, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
481 'OpImageSparseRead': (320, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
482 'OpImageSparseSampleDrefExplicitLod': (308, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))),
483 'OpImageSparseSampleDrefImplicitLod': (307, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
484 'OpImageSparseSampleExplicitLod': (306, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))),
485 'OpImageSparseSampleImplicitLod': (305, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
486 'OpImageSparseSampleProjDrefExplicitLod': (312, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))),
487 'OpImageSparseSampleProjDrefImplicitLod': (311, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
488 'OpImageSparseSampleProjExplicitLod': (310, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', ''))),
489 'OpImageSparseSampleProjImplicitLod': (309, True, True, (('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
490 'OpImageSparseTexelsResident': (316, True, True, (('IdRef', ''),)),
491 'OpImageTexelPointer': (60, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
492 'OpImageWrite': (99, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('ImageOperands', '?'))),
493 'OpInBoundsAccessChain': (66, True, True, (('IdRef', ''), ('IdRef', '*'))),
494 'OpInBoundsPtrAccessChain': (70, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))),
495 'OpIsFinite': (158, True, True, (('IdRef', ''),)),
496 'OpIsHelperInvocationEXT': (5381, True, True, ()),
497 'OpIsInf': (157, True, True, (('IdRef', ''),)),
498 'OpIsNan': (156, True, True, (('IdRef', ''),)),
499 'OpIsNodePayloadValidAMDX': (5101, True, True, (('IdRef', ''), ('IdRef', ''))),
500 'OpIsNormal': (159, True, True, (('IdRef', ''),)),
501 'OpIsValidEvent': (300, True, True, (('IdRef', ''),)),
502 'OpIsValidReserveId': (282, True, True, (('IdRef', ''),)),
503 'OpKill': (252, False, False, ()),
504 'OpLabel': (248, False, True, ()),
505 'OpLessOrGreater': (161, True, True, (('IdRef', ''), ('IdRef', ''))),
506 'OpLifetimeStart': (256, False, False, (('IdRef', ''), ('LiteralInteger', ''))),
507 'OpLifetimeStop': (257, False, False, (('IdRef', ''), ('LiteralInteger', ''))),
508 'OpLine': (8, False, False, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
509 'OpLoad': (61, True, True, (('IdRef', ''), ('MemoryAccess', '?'))),
510 'OpLogicalAnd': (167, True, True, (('IdRef', ''), ('IdRef', ''))),
511 'OpLogicalEqual': (164, True, True, (('IdRef', ''), ('IdRef', ''))),
512 'OpLogicalNot': (168, True, True, (('IdRef', ''),)),
513 'OpLogicalNotEqual': (165, True, True, (('IdRef', ''), ('IdRef', ''))),
514 'OpLogicalOr': (166, True, True, (('IdRef', ''), ('IdRef', ''))),
515 'OpLoopControlINTEL': (5887, False, False, (('LiteralInteger', '*'),)),
516 'OpLoopMerge': (246, False, False, (('IdRef', ''), ('IdRef', ''), ('LoopControl', ''))),
517 'OpMaskedGatherINTEL': (6428, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''), ('IdRef', ''))),
518 'OpMaskedScatterINTEL': (6429, False, False, (('IdRef', ''), ('IdRef', ''), ('LiteralInteger', ''), ('IdRef', ''))),
519 'OpMatrixTimesMatrix': (146, True, True, (('IdRef', ''), ('IdRef', ''))),
520 'OpMatrixTimesScalar': (143, True, True, (('IdRef', ''), ('IdRef', ''))),
521 'OpMatrixTimesVector': (145, True, True, (('IdRef', ''), ('IdRef', ''))),
522 'OpMemberDecorate': (72, False, False, (('IdRef', ''), ('LiteralInteger', ''), ('Decoration', ''))),
523 'OpMemberDecorateIdEXT': (5127, False, False, (('IdRef', ''), ('LiteralInteger', ''), ('Decoration', ''))),
524 'OpMemberDecorateString': (5633, False, False, (('IdRef', ''), ('LiteralInteger', ''), ('Decoration', ''))),
525 'OpMemberName': (6, False, False, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralString', ''))),
526 'OpMemoryBarrier': (225, False, False, (('IdScope', ''), ('IdMemorySemantics', ''))),
527 'OpMemoryModel': (14, False, False, (('AddressingModel', ''), ('MemoryModel', ''))),
528 'OpMemoryNamedBarrier': (329, False, False, (('IdRef', ''), ('IdScope', ''), ('IdMemorySemantics', ''))),
529 'OpModuleProcessed': (330, False, False, (('LiteralString', ''),)),
530 'OpName': (5, False, False, (('IdRef', ''), ('LiteralString', ''))),
531 'OpNamedBarrierInitialize': (328, True, True, (('IdRef', ''),)),
532 'OpNoLine': (317, False, False, ()),
533 'OpNodePayloadArrayLengthAMDX': (5090, True, True, (('IdRef', ''),)),
534 'OpNop': (0, False, False, ()),
535 'OpNot': (200, True, True, (('IdRef', ''),)),
536 'OpOrdered': (162, True, True, (('IdRef', ''), ('IdRef', ''))),
537 'OpOuterProduct': (147, True, True, (('IdRef', ''), ('IdRef', ''))),
538 'OpPauseINTEL': (6267, False, False, (('IdRef', ''),)),
539 'OpPhi': (245, True, True, (('PairIdRefIdRef', '*'),)),
540 'OpPoisonKHR': (5158, True, True, ()),
541 'OpPredicatedLoadINTEL': (6258, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))),
542 'OpPredicatedStoreINTEL': (6259, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))),
543 'OpPtrAccessChain': (67, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))),
544 'OpPtrCastToCrossWorkgroupALTERA': (5934, True, True, (('IdRef', ''),)),
545 'OpPtrCastToGeneric': (121, True, True, (('IdRef', ''),)),
546 'OpPtrDiff': (403, True, True, (('IdRef', ''), ('IdRef', ''))),
547 'OpPtrEqual': (401, True, True, (('IdRef', ''), ('IdRef', ''))),
548 'OpPtrNotEqual': (402, True, True, (('IdRef', ''), ('IdRef', ''))),
549 'OpQuantizeToF16': (116, True, True, (('IdRef', ''),)),
550 'OpRawAccessChainNV': (5398, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('RawAccessChainOperands', '?'))),
551 'OpRayQueryConfirmIntersectionKHR': (4476, False, False, (('IdRef', ''),)),
552 'OpRayQueryGenerateIntersectionKHR': (4475, False, False, (('IdRef', ''), ('IdRef', ''))),
553 'OpRayQueryGetIntersectionBarycentricsKHR': (6024, True, True, (('IdRef', ''), ('IdRef', ''))),
554 'OpRayQueryGetIntersectionCandidateAABBOpaqueKHR': (6026, True, True, (('IdRef', ''),)),
555 'OpRayQueryGetIntersectionClusterIdNV': (5345, True, True, (('IdRef', ''), ('IdRef', ''))),
556 'OpRayQueryGetIntersectionFrontFaceKHR': (6025, True, True, (('IdRef', ''), ('IdRef', ''))),
557 'OpRayQueryGetIntersectionGeometryIndexKHR': (6022, True, True, (('IdRef', ''), ('IdRef', ''))),
558 'OpRayQueryGetIntersectionInstanceCustomIndexAtLevelAMDX': (5198, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
559 'OpRayQueryGetIntersectionInstanceCustomIndexKHR': (6019, True, True, (('IdRef', ''), ('IdRef', ''))),
560 'OpRayQueryGetIntersectionInstanceIdAtLevelAMDX': (5199, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
561 'OpRayQueryGetIntersectionInstanceIdKHR': (6020, True, True, (('IdRef', ''), ('IdRef', ''))),
562 'OpRayQueryGetIntersectionInstanceLevelAMDX': (5197, True, True, (('IdRef', ''), ('IdRef', ''))),
563 'OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR': (6021, True, True, (('IdRef', ''), ('IdRef', ''))),
564 'OpRayQueryGetIntersectionLSSHitValueNV': (5431, True, True, (('IdRef', ''), ('IdRef', ''))),
565 'OpRayQueryGetIntersectionLSSPositionsNV': (5429, True, True, (('IdRef', ''), ('IdRef', ''))),
566 'OpRayQueryGetIntersectionLSSRadiiNV': (5430, True, True, (('IdRef', ''), ('IdRef', ''))),
567 'OpRayQueryGetIntersectionObjectRayDirectionKHR': (6027, True, True, (('IdRef', ''), ('IdRef', ''))),
568 'OpRayQueryGetIntersectionObjectRayOriginKHR': (6028, True, True, (('IdRef', ''), ('IdRef', ''))),
569 'OpRayQueryGetIntersectionObjectToWorldAtLevelAMDX': (5200, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
570 'OpRayQueryGetIntersectionObjectToWorldKHR': (6031, True, True, (('IdRef', ''), ('IdRef', ''))),
571 'OpRayQueryGetIntersectionPrimitiveIndexKHR': (6023, True, True, (('IdRef', ''), ('IdRef', ''))),
572 'OpRayQueryGetIntersectionSpherePositionNV': (5427, True, True, (('IdRef', ''), ('IdRef', ''))),
573 'OpRayQueryGetIntersectionSphereRadiusNV': (5428, True, True, (('IdRef', ''), ('IdRef', ''))),
574 'OpRayQueryGetIntersectionTKHR': (6018, True, True, (('IdRef', ''), ('IdRef', ''))),
575 'OpRayQueryGetIntersectionTriangleVertexPositionsKHR': (5340, True, True, (('IdRef', ''), ('IdRef', ''))),
576 'OpRayQueryGetIntersectionTypeKHR': (4479, True, True, (('IdRef', ''), ('IdRef', ''))),
577 'OpRayQueryGetIntersectionWorldToObjectAtLevelAMDX': (5201, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
578 'OpRayQueryGetIntersectionWorldToObjectKHR': (6032, True, True, (('IdRef', ''), ('IdRef', ''))),
579 'OpRayQueryGetRayFlagsKHR': (6017, True, True, (('IdRef', ''),)),
580 'OpRayQueryGetRayTMinKHR': (6016, True, True, (('IdRef', ''),)),
581 'OpRayQueryGetWorldRayDirectionKHR': (6029, True, True, (('IdRef', ''),)),
582 'OpRayQueryGetWorldRayOriginKHR': (6030, True, True, (('IdRef', ''),)),
583 'OpRayQueryInitializeKHR': (4473, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
584 'OpRayQueryIsLSSHitNV': (5439, True, True, (('IdRef', ''), ('IdRef', ''))),
585 'OpRayQueryIsSphereHitNV': (5438, True, True, (('IdRef', ''), ('IdRef', ''))),
586 'OpRayQueryProceedKHR': (4477, True, True, (('IdRef', ''),)),
587 'OpRayQueryTerminateKHR': (4474, False, False, (('IdRef', ''),)),
588 'OpReadClockKHR': (5056, True, True, (('IdScope', ''),)),
589 'OpReadPipe': (274, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
590 'OpReadPipeBlockingALTERA': (5946, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
591 'OpReleaseEvent': (298, False, False, (('IdRef', ''),)),
592 'OpReorderThreadWithHintEXT': (5314, False, False, (('IdRef', ''), ('IdRef', ''))),
593 'OpReorderThreadWithHintNV': (5280, False, False, (('IdRef', ''), ('IdRef', ''))),
594 'OpReorderThreadWithHitObjectEXT': (5315, False, False, (('IdRef', ''), ('IdRef', '?'), ('IdRef', '?'))),
595 'OpReorderThreadWithHitObjectNV': (5279, False, False, (('IdRef', ''), ('IdRef', '?'), ('IdRef', '?'))),
596 'OpReportIntersectionKHR': (5334, True, True, (('IdRef', ''), ('IdRef', ''))),
597 'OpReserveReadPipePackets': (278, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
598 'OpReserveWritePipePackets': (279, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
599 'OpReservedReadPipe': (276, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
600 'OpReservedWritePipe': (277, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
601 'OpRestoreMemoryINTEL': (5820, False, False, (('IdRef', ''),)),
602 'OpRetainEvent': (297, False, False, (('IdRef', ''),)),
603 'OpReturn': (253, False, False, ()),
604 'OpReturnValue': (254, False, False, (('IdRef', ''),)),
605 'OpRoundFToTF32INTEL': (6426, True, True, (('IdRef', ''),)),
606 'OpSConvert': (114, True, True, (('IdRef', ''),)),
607 'OpSDiv': (135, True, True, (('IdRef', ''), ('IdRef', ''))),
608 'OpSDot': (4450, True, True, (('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))),
609 'OpSDotAccSat': (4453, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))),
610 'OpSGreaterThan': (173, True, True, (('IdRef', ''), ('IdRef', ''))),
611 'OpSGreaterThanEqual': (175, True, True, (('IdRef', ''), ('IdRef', ''))),
612 'OpSLessThan': (177, True, True, (('IdRef', ''), ('IdRef', ''))),
613 'OpSLessThanEqual': (179, True, True, (('IdRef', ''), ('IdRef', ''))),
614 'OpSMod': (139, True, True, (('IdRef', ''), ('IdRef', ''))),
615 'OpSMulExtended': (152, True, True, (('IdRef', ''), ('IdRef', ''))),
616 'OpSNegate': (126, True, True, (('IdRef', ''),)),
617 'OpSRem': (138, True, True, (('IdRef', ''), ('IdRef', ''))),
618 'OpSUDot': (4452, True, True, (('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))),
619 'OpSUDotAccSat': (4455, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))),
620 'OpSampledImage': (86, True, True, (('IdRef', ''), ('IdRef', ''))),
621 'OpSamplerImageAddressingModeNV': (5397, False, False, (('LiteralInteger', ''),)),
622 'OpSatConvertSToU': (118, True, True, (('IdRef', ''),)),
623 'OpSatConvertUToS': (119, True, True, (('IdRef', ''),)),
624 'OpSaveMemoryINTEL': (5819, True, True, ()),
625 'OpSelect': (169, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
626 'OpSelectionMerge': (247, False, False, (('IdRef', ''), ('SelectionControl', ''))),
627 'OpSetMeshOutputsEXT': (5295, False, False, (('IdRef', ''), ('IdRef', ''))),
628 'OpSetUserEventStatus': (301, False, False, (('IdRef', ''), ('IdRef', ''))),
629 'OpShiftLeftLogical': (196, True, True, (('IdRef', ''), ('IdRef', ''))),
630 'OpShiftRightArithmetic': (195, True, True, (('IdRef', ''), ('IdRef', ''))),
631 'OpShiftRightLogical': (194, True, True, (('IdRef', ''), ('IdRef', ''))),
632 'OpSignBitSet': (160, True, True, (('IdRef', ''),)),
633 'OpSizeOf': (321, True, True, (('IdRef', ''),)),
634 'OpSource': (3, False, False, (('SourceLanguage', ''), ('LiteralInteger', ''), ('IdRef', '?'), ('LiteralString', '?'))),
635 'OpSourceContinued': (2, False, False, (('LiteralString', ''),)),
636 'OpSourceExtension': (4, False, False, (('LiteralString', ''),)),
637 'OpSpecConstant': (50, True, True, (('LiteralContextDependentNumber', ''),)),
638 'OpSpecConstantArchitectureINTEL': (6252, True, True, (('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
639 'OpSpecConstantCapabilitiesINTEL': (6253, True, True, (('Capability', '*'),)),
640 'OpSpecConstantComposite': (51, True, True, (('IdRef', '*'),)),
641 'OpSpecConstantCompositeContinuedINTEL': (6092, False, False, (('IdRef', '*'),)),
642 'OpSpecConstantCompositeReplicateEXT': (4462, True, True, (('IdRef', ''),)),
643 'OpSpecConstantDataKHR': (5148, True, True, (('LiteralInteger', '*'),)),
644 'OpSpecConstantFalse': (49, True, True, ()),
645 'OpSpecConstantOp': (52, True, True, (('LiteralSpecConstantOpInteger', ''),)),
646 'OpSpecConstantStringAMDX': (5104, False, True, (('LiteralString', ''),)),
647 'OpSpecConstantTargetINTEL': (6251, True, True, (('LiteralInteger', ''), ('LiteralInteger', '*'))),
648 'OpSpecConstantTrue': (48, True, True, ()),
649 'OpStencilAttachmentReadEXT': (4162, True, True, (('IdRef', '?'),)),
650 'OpStochasticRoundFToFINTEL': (6217, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '?'))),
651 'OpStore': (62, False, False, (('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))),
652 'OpString': (7, False, True, (('LiteralString', ''),)),
653 'OpSubgroup2DBlockLoadINTEL': (6231, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
654 'OpSubgroup2DBlockLoadTransformINTEL': (6232, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
655 'OpSubgroup2DBlockLoadTransposeINTEL': (6233, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
656 'OpSubgroup2DBlockPrefetchINTEL': (6234, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
657 'OpSubgroup2DBlockStoreINTEL': (6235, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
658 'OpSubgroupAllEqualKHR': (4430, True, True, (('IdRef', ''),)),
659 'OpSubgroupAllKHR': (4428, True, True, (('IdRef', ''),)),
660 'OpSubgroupAnyKHR': (4429, True, True, (('IdRef', ''),)),
661 'OpSubgroupAvcBmeInitializeINTEL': (5782, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
662 'OpSubgroupAvcFmeInitializeINTEL': (5781, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
663 'OpSubgroupAvcImeAdjustRefOffsetINTEL': (5751, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
664 'OpSubgroupAvcImeConvertToMcePayloadINTEL': (5752, True, True, (('IdRef', ''),)),
665 'OpSubgroupAvcImeConvertToMceResultINTEL': (5765, True, True, (('IdRef', ''),)),
666 'OpSubgroupAvcImeEvaluateWithDualReferenceINTEL': (5758, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
667 'OpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL': (5760, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
668 'OpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL': (5764, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
669 'OpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL': (5762, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
670 'OpSubgroupAvcImeEvaluateWithSingleReferenceINTEL': (5757, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
671 'OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL': (5759, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
672 'OpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL': (5763, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
673 'OpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL': (5761, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
674 'OpSubgroupAvcImeGetBorderReachedINTEL': (5776, True, True, (('IdRef', ''), ('IdRef', ''))),
675 'OpSubgroupAvcImeGetDualReferenceStreaminINTEL': (5767, True, True, (('IdRef', ''),)),
676 'OpSubgroupAvcImeGetSingleReferenceStreaminINTEL': (5766, True, True, (('IdRef', ''),)),
677 'OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL': (5774, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
678 'OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL': (5773, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
679 'OpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL': (5775, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
680 'OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL': (5771, True, True, (('IdRef', ''), ('IdRef', ''))),
681 'OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL': (5770, True, True, (('IdRef', ''), ('IdRef', ''))),
682 'OpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL': (5772, True, True, (('IdRef', ''), ('IdRef', ''))),
683 'OpSubgroupAvcImeGetTruncatedSearchIndicationINTEL': (5777, True, True, (('IdRef', ''),)),
684 'OpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL': (5778, True, True, (('IdRef', ''),)),
685 'OpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL': (5780, True, True, (('IdRef', ''),)),
686 'OpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL': (5779, True, True, (('IdRef', ''),)),
687 'OpSubgroupAvcImeInitializeINTEL': (5747, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
688 'OpSubgroupAvcImeRefWindowSizeINTEL': (5750, True, True, (('IdRef', ''), ('IdRef', ''))),
689 'OpSubgroupAvcImeSetDualReferenceINTEL': (5749, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
690 'OpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL': (5755, True, True, (('IdRef', ''), ('IdRef', ''))),
691 'OpSubgroupAvcImeSetMaxMotionVectorCountINTEL': (5753, True, True, (('IdRef', ''), ('IdRef', ''))),
692 'OpSubgroupAvcImeSetSingleReferenceINTEL': (5748, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
693 'OpSubgroupAvcImeSetUnidirectionalMixDisableINTEL': (5754, True, True, (('IdRef', ''),)),
694 'OpSubgroupAvcImeSetWeightedSadINTEL': (5756, True, True, (('IdRef', ''), ('IdRef', ''))),
695 'OpSubgroupAvcImeStripDualReferenceStreamoutINTEL': (5769, True, True, (('IdRef', ''),)),
696 'OpSubgroupAvcImeStripSingleReferenceStreamoutINTEL': (5768, True, True, (('IdRef', ''),)),
697 'OpSubgroupAvcMceConvertToImePayloadINTEL': (5732, True, True, (('IdRef', ''),)),
698 'OpSubgroupAvcMceConvertToImeResultINTEL': (5733, True, True, (('IdRef', ''),)),
699 'OpSubgroupAvcMceConvertToRefPayloadINTEL': (5734, True, True, (('IdRef', ''),)),
700 'OpSubgroupAvcMceConvertToRefResultINTEL': (5735, True, True, (('IdRef', ''),)),
701 'OpSubgroupAvcMceConvertToSicPayloadINTEL': (5736, True, True, (('IdRef', ''),)),
702 'OpSubgroupAvcMceConvertToSicResultINTEL': (5737, True, True, (('IdRef', ''),)),
703 'OpSubgroupAvcMceGetBestInterDistortionsINTEL': (5740, True, True, (('IdRef', ''),)),
704 'OpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL': (5721, True, True, ()),
705 'OpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL': (5713, True, True, (('IdRef', ''), ('IdRef', ''))),
706 'OpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL': (5717, True, True, (('IdRef', ''), ('IdRef', ''))),
707 'OpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL': (5720, True, True, (('IdRef', ''), ('IdRef', ''))),
708 'OpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL': (5715, True, True, (('IdRef', ''), ('IdRef', ''))),
709 'OpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL': (5727, True, True, ()),
710 'OpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL': (5725, True, True, (('IdRef', ''), ('IdRef', ''))),
711 'OpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL': (5719, True, True, (('IdRef', ''), ('IdRef', ''))),
712 'OpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL': (5723, True, True, ()),
713 'OpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL': (5722, True, True, ()),
714 'OpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL': (5726, True, True, ()),
715 'OpSubgroupAvcMceGetInterDirectionsINTEL': (5743, True, True, (('IdRef', ''),)),
716 'OpSubgroupAvcMceGetInterDistortionsINTEL': (5739, True, True, (('IdRef', ''),)),
717 'OpSubgroupAvcMceGetInterMajorShapeINTEL': (5741, True, True, (('IdRef', ''),)),
718 'OpSubgroupAvcMceGetInterMinorShapeINTEL': (5742, True, True, (('IdRef', ''),)),
719 'OpSubgroupAvcMceGetInterMotionVectorCountINTEL': (5744, True, True, (('IdRef', ''),)),
720 'OpSubgroupAvcMceGetInterReferenceIdsINTEL': (5745, True, True, (('IdRef', ''),)),
721 'OpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL': (5746, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
722 'OpSubgroupAvcMceGetMotionVectorsINTEL': (5738, True, True, (('IdRef', ''),)),
723 'OpSubgroupAvcMceSetAcOnlyHaarINTEL': (5728, True, True, (('IdRef', ''),)),
724 'OpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL': (5731, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
725 'OpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL': (5714, True, True, (('IdRef', ''), ('IdRef', ''))),
726 'OpSubgroupAvcMceSetInterDirectionPenaltyINTEL': (5718, True, True, (('IdRef', ''), ('IdRef', ''))),
727 'OpSubgroupAvcMceSetInterShapePenaltyINTEL': (5716, True, True, (('IdRef', ''), ('IdRef', ''))),
728 'OpSubgroupAvcMceSetMotionVectorCostFunctionINTEL': (5724, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
729 'OpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL': (5730, True, True, (('IdRef', ''), ('IdRef', ''))),
730 'OpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL': (5729, True, True, (('IdRef', ''), ('IdRef', ''))),
731 'OpSubgroupAvcRefConvertToMcePayloadINTEL': (5783, True, True, (('IdRef', ''),)),
732 'OpSubgroupAvcRefConvertToMceResultINTEL': (5790, True, True, (('IdRef', ''),)),
733 'OpSubgroupAvcRefEvaluateWithDualReferenceINTEL': (5787, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
734 'OpSubgroupAvcRefEvaluateWithMultiReferenceINTEL': (5788, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
735 'OpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL': (5789, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
736 'OpSubgroupAvcRefEvaluateWithSingleReferenceINTEL': (5786, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
737 'OpSubgroupAvcRefSetBidirectionalMixDisableINTEL': (5784, True, True, (('IdRef', ''),)),
738 'OpSubgroupAvcRefSetBilinearFilterEnableINTEL': (5785, True, True, (('IdRef', ''),)),
739 'OpSubgroupAvcSicConfigureIpeLumaChromaINTEL': (5794, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
740 'OpSubgroupAvcSicConfigureIpeLumaINTEL': (5793, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
741 'OpSubgroupAvcSicConfigureSkcINTEL': (5792, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
742 'OpSubgroupAvcSicConvertToMcePayloadINTEL': (5796, True, True, (('IdRef', ''),)),
743 'OpSubgroupAvcSicConvertToMceResultINTEL': (5808, True, True, (('IdRef', ''),)),
744 'OpSubgroupAvcSicEvaluateIpeINTEL': (5803, True, True, (('IdRef', ''), ('IdRef', ''))),
745 'OpSubgroupAvcSicEvaluateWithDualReferenceINTEL': (5805, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
746 'OpSubgroupAvcSicEvaluateWithMultiReferenceINTEL': (5806, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
747 'OpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL': (5807, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
748 'OpSubgroupAvcSicEvaluateWithSingleReferenceINTEL': (5804, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
749 'OpSubgroupAvcSicGetBestIpeChromaDistortionINTEL': (5811, True, True, (('IdRef', ''),)),
750 'OpSubgroupAvcSicGetBestIpeLumaDistortionINTEL': (5810, True, True, (('IdRef', ''),)),
751 'OpSubgroupAvcSicGetInterRawSadsINTEL': (5816, True, True, (('IdRef', ''),)),
752 'OpSubgroupAvcSicGetIpeChromaModeINTEL': (5813, True, True, (('IdRef', ''),)),
753 'OpSubgroupAvcSicGetIpeLumaShapeINTEL': (5809, True, True, (('IdRef', ''),)),
754 'OpSubgroupAvcSicGetMotionVectorMaskINTEL': (5795, True, True, (('IdRef', ''), ('IdRef', ''))),
755 'OpSubgroupAvcSicGetPackedIpeLumaModesINTEL': (5812, True, True, (('IdRef', ''),)),
756 'OpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL': (5814, True, True, (('IdRef', ''),)),
757 'OpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL': (5815, True, True, (('IdRef', ''),)),
758 'OpSubgroupAvcSicInitializeINTEL': (5791, True, True, (('IdRef', ''),)),
759 'OpSubgroupAvcSicSetBilinearFilterEnableINTEL': (5800, True, True, (('IdRef', ''),)),
760 'OpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL': (5802, True, True, (('IdRef', ''), ('IdRef', ''))),
761 'OpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL': (5799, True, True, (('IdRef', ''), ('IdRef', ''))),
762 'OpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL': (5798, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
763 'OpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL': (5797, True, True, (('IdRef', ''), ('IdRef', ''))),
764 'OpSubgroupAvcSicSetSkcForwardTransformEnableINTEL': (5801, True, True, (('IdRef', ''), ('IdRef', ''))),
765 'OpSubgroupBallotKHR': (4421, True, True, (('IdRef', ''),)),
766 'OpSubgroupBitcastShuffleINTEL': (6208, True, True, (('IdRef', ''),)),
767 'OpSubgroupBlockPrefetchINTEL': (6221, False, False, (('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'))),
768 'OpSubgroupBlockReadINTEL': (5575, True, True, (('IdRef', ''),)),
769 'OpSubgroupBlockWriteINTEL': (5576, False, False, (('IdRef', ''), ('IdRef', ''))),
770 'OpSubgroupFirstInvocationKHR': (4422, True, True, (('IdRef', ''),)),
771 'OpSubgroupImageBlockReadINTEL': (5577, True, True, (('IdRef', ''), ('IdRef', ''))),
772 'OpSubgroupImageBlockWriteINTEL': (5578, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
773 'OpSubgroupImageMediaBlockReadINTEL': (5580, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
774 'OpSubgroupImageMediaBlockWriteINTEL': (5581, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
775 'OpSubgroupMatrixMultiplyAccumulateINTEL': (6237, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MatrixMultiplyAccumulateOperands', '?'))),
776 'OpSubgroupReadInvocationKHR': (4432, True, True, (('IdRef', ''), ('IdRef', ''))),
777 'OpSubgroupShuffleDownINTEL': (5572, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
778 'OpSubgroupShuffleINTEL': (5571, True, True, (('IdRef', ''), ('IdRef', ''))),
779 'OpSubgroupShuffleUpINTEL': (5573, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
780 'OpSubgroupShuffleXorINTEL': (5574, True, True, (('IdRef', ''), ('IdRef', ''))),
781 'OpSwitch': (251, False, False, (('IdRef', ''), ('IdRef', ''), ('PairLiteralIntegerIdRef', '*'))),
782 'OpTaskSequenceAsyncALTERA': (6164, False, False, (('IdRef', ''), ('IdRef', '*'))),
783 'OpTaskSequenceCreateALTERA': (6163, True, True, (('IdRef', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''))),
784 'OpTaskSequenceGetALTERA': (6165, True, True, (('IdRef', ''),)),
785 'OpTaskSequenceReleaseALTERA': (6166, False, False, (('IdRef', ''),)),
786 'OpTensorLayoutSetBlockSizeNV': (5384, True, True, (('IdRef', ''), ('IdRef', '*'))),
787 'OpTensorLayoutSetClampValueNV': (5376, True, True, (('IdRef', ''), ('IdRef', ''))),
788 'OpTensorLayoutSetDimensionNV': (5373, True, True, (('IdRef', ''), ('IdRef', '*'))),
789 'OpTensorLayoutSetStrideNV': (5374, True, True, (('IdRef', ''), ('IdRef', '*'))),
790 'OpTensorLayoutSliceNV': (5375, True, True, (('IdRef', ''), ('IdRef', '*'))),
791 'OpTensorQuerySizeARM': (4166, True, True, (('IdRef', ''), ('IdRef', ''))),
792 'OpTensorReadARM': (4164, True, True, (('IdRef', ''), ('IdRef', ''), ('TensorOperands', '?'))),
793 'OpTensorViewSetClipNV': (5382, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
794 'OpTensorViewSetDimensionNV': (5378, True, True, (('IdRef', ''), ('IdRef', '*'))),
795 'OpTensorViewSetStrideNV': (5379, True, True, (('IdRef', ''), ('IdRef', '*'))),
796 'OpTensorWriteARM': (4165, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('TensorOperands', '?'))),
797 'OpTerminateInvocation': (4416, False, False, ()),
798 'OpTerminateRayKHR': (4449, False, False, ()),
799 'OpTerminateRayNV': (5336, False, False, ()),
800 'OpTraceMotionNV': (5338, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
801 'OpTraceNV': (5337, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
802 'OpTraceRayKHR': (4445, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
803 'OpTraceRayMotionNV': (5339, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
804 'OpTranspose': (84, True, True, (('IdRef', ''),)),
805 'OpTypeAccelerationStructureKHR': (5341, False, True, ()),
806 'OpTypeArray': (28, False, True, (('IdRef', ''), ('IdRef', ''))),
807 'OpTypeAvcImeDualReferenceStreaminINTEL': (5710, False, True, ()),
808 'OpTypeAvcImePayloadINTEL': (5701, False, True, ()),
809 'OpTypeAvcImeResultDualReferenceStreamoutINTEL': (5708, False, True, ()),
810 'OpTypeAvcImeResultINTEL': (5706, False, True, ()),
811 'OpTypeAvcImeResultSingleReferenceStreamoutINTEL': (5707, False, True, ()),
812 'OpTypeAvcImeSingleReferenceStreaminINTEL': (5709, False, True, ()),
813 'OpTypeAvcMcePayloadINTEL': (5704, False, True, ()),
814 'OpTypeAvcMceResultINTEL': (5705, False, True, ()),
815 'OpTypeAvcRefPayloadINTEL': (5702, False, True, ()),
816 'OpTypeAvcRefResultINTEL': (5711, False, True, ()),
817 'OpTypeAvcSicPayloadINTEL': (5703, False, True, ()),
818 'OpTypeAvcSicResultINTEL': (5712, False, True, ()),
819 'OpTypeBool': (20, False, True, ()),
820 'OpTypeBufferEXT': (5115, False, True, (('StorageClass', ''),)),
821 'OpTypeBufferSurfaceINTEL': (6086, False, True, (('AccessQualifier', ''),)),
822 'OpTypeCooperativeMatrixKHR': (4456, False, True, (('IdRef', ''), ('IdScope', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
823 'OpTypeCooperativeMatrixNV': (5358, False, True, (('IdRef', ''), ('IdScope', ''), ('IdRef', ''), ('IdRef', ''))),
824 'OpTypeDeviceEvent': (35, False, True, ()),
825 'OpTypeEvent': (34, False, True, ()),
826 'OpTypeFloat': (22, False, True, (('LiteralInteger', ''), ('FPEncoding', '?'))),
827 'OpTypeForwardPointer': (39, False, False, (('IdRef', ''), ('StorageClass', ''))),
828 'OpTypeFunction': (33, False, True, (('IdRef', ''), ('IdRef', '*'))),
829 'OpTypeGraphARM': (4190, False, True, (('LiteralInteger', ''), ('IdRef', '*'))),
830 'OpTypeHitObjectEXT': (5313, False, True, ()),
831 'OpTypeHitObjectNV': (5281, False, True, ()),
832 'OpTypeImage': (25, False, True, (('IdRef', ''), ('Dim', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('LiteralInteger', ''), ('ImageFormat', ''), ('AccessQualifier', '?'))),
833 'OpTypeInt': (21, False, True, (('LiteralInteger', ''), ('LiteralInteger', ''))),
834 'OpTypeMatrix': (24, False, True, (('IdRef', ''), ('LiteralInteger', ''))),
835 'OpTypeNamedBarrier': (327, False, True, ()),
836 'OpTypeNodePayloadArrayAMDX': (5076, False, True, (('IdRef', ''),)),
837 'OpTypeOpaque': (31, False, True, (('LiteralString', ''),)),
838 'OpTypePipe': (38, False, True, (('AccessQualifier', ''),)),
839 'OpTypePipeStorage': (322, False, True, ()),
840 'OpTypePointer': (32, False, True, (('StorageClass', ''), ('IdRef', ''))),
841 'OpTypeQueue': (37, False, True, ()),
842 'OpTypeRayQueryKHR': (4472, False, True, ()),
843 'OpTypeReserveId': (36, False, True, ()),
844 'OpTypeRuntimeArray': (29, False, True, (('IdRef', ''),)),
845 'OpTypeSampledImage': (27, False, True, (('IdRef', ''),)),
846 'OpTypeSampler': (26, False, True, ()),
847 'OpTypeStruct': (30, False, True, (('IdRef', '*'),)),
848 'OpTypeStructContinuedINTEL': (6090, False, False, (('IdRef', '*'),)),
849 'OpTypeTaskSequenceALTERA': (6199, False, True, ()),
850 'OpTypeTensorARM': (4163, False, True, (('IdRef', ''), ('IdRef', '?'), ('IdRef', '?'))),
851 'OpTypeTensorLayoutNV': (5370, False, True, (('IdRef', ''), ('IdRef', ''))),
852 'OpTypeTensorViewNV': (5371, False, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))),
853 'OpTypeUntypedPointerKHR': (4417, False, True, (('StorageClass', ''),)),
854 'OpTypeVector': (23, False, True, (('IdRef', ''), ('LiteralInteger', ''))),
855 'OpTypeVectorIdEXT': (5288, False, True, (('IdRef', ''), ('IdRef', ''))),
856 'OpTypeVmeImageINTEL': (5700, False, True, (('IdRef', ''),)),
857 'OpTypeVoid': (19, False, True, ()),
858 'OpUAddSatINTEL': (5590, True, True, (('IdRef', ''), ('IdRef', ''))),
859 'OpUAverageINTEL': (5592, True, True, (('IdRef', ''), ('IdRef', ''))),
860 'OpUAverageRoundedINTEL': (5594, True, True, (('IdRef', ''), ('IdRef', ''))),
861 'OpUConvert': (113, True, True, (('IdRef', ''),)),
862 'OpUCountLeadingZerosINTEL': (5585, True, True, (('IdRef', ''),)),
863 'OpUCountTrailingZerosINTEL': (5586, True, True, (('IdRef', ''),)),
864 'OpUDiv': (134, True, True, (('IdRef', ''), ('IdRef', ''))),
865 'OpUDot': (4451, True, True, (('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))),
866 'OpUDotAccSat': (4454, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('PackedVectorFormat', '?'))),
867 'OpUGreaterThan': (172, True, True, (('IdRef', ''), ('IdRef', ''))),
868 'OpUGreaterThanEqual': (174, True, True, (('IdRef', ''), ('IdRef', ''))),
869 'OpULessThan': (176, True, True, (('IdRef', ''), ('IdRef', ''))),
870 'OpULessThanEqual': (178, True, True, (('IdRef', ''), ('IdRef', ''))),
871 'OpUMod': (137, True, True, (('IdRef', ''), ('IdRef', ''))),
872 'OpUMul32x16INTEL': (5598, True, True, (('IdRef', ''), ('IdRef', ''))),
873 'OpUMulExtended': (151, True, True, (('IdRef', ''), ('IdRef', ''))),
874 'OpUSubSatINTEL': (5596, True, True, (('IdRef', ''), ('IdRef', ''))),
875 'OpUndef': (1, True, True, ()),
876 'OpUnordered': (163, True, True, (('IdRef', ''), ('IdRef', ''))),
877 'OpUnreachable': (255, False, False, ()),
878 'OpUntypedAccessChainKHR': (4419, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))),
879 'OpUntypedArrayLengthKHR': (4425, True, True, (('IdRef', ''), ('IdRef', ''), ('LiteralInteger', ''))),
880 'OpUntypedGroupAsyncCopyKHR': (4434, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('MemoryAccess', '?'), ('MemoryAccess', '?'))),
881 'OpUntypedImageTexelPointerEXT': (5126, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
882 'OpUntypedInBoundsAccessChainKHR': (4420, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))),
883 'OpUntypedInBoundsPtrAccessChainKHR': (4424, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))),
884 'OpUntypedPrefetchKHR': (4426, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', '?'), ('IdRef', '?'), ('IdRef', '?'))),
885 'OpUntypedPtrAccessChainKHR': (4423, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', '*'))),
886 'OpUntypedVariableKHR': (4418, True, True, (('StorageClass', ''), ('IdRef', '?'), ('IdRef', '?'))),
887 'OpUntypedVariableLengthArrayINTEL': (6244, True, True, (('IdRef', ''), ('IdRef', ''))),
888 'OpVariable': (59, True, True, (('StorageClass', ''), ('IdRef', '?'))),
889 'OpVariableLengthArrayINTEL': (5818, True, True, (('IdRef', ''),)),
890 'OpVectorExtractDynamic': (77, True, True, (('IdRef', ''), ('IdRef', ''))),
891 'OpVectorInsertDynamic': (78, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
892 'OpVectorShuffle': (79, True, True, (('IdRef', ''), ('IdRef', ''), ('LiteralInteger', '*'))),
893 'OpVectorTimesMatrix': (144, True, True, (('IdRef', ''), ('IdRef', ''))),
894 'OpVectorTimesScalar': (142, True, True, (('IdRef', ''), ('IdRef', ''))),
895 'OpVmeImageINTEL': (5699, True, True, (('IdRef', ''), ('IdRef', ''))),
896 'OpWritePackedPrimitiveIndices4x8NV': (5299, False, False, (('IdRef', ''), ('IdRef', ''))),
897 'OpWritePipe': (275, True, True, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
898 'OpWritePipeBlockingALTERA': (5947, False, False, (('IdRef', ''), ('IdRef', ''), ('IdRef', ''), ('IdRef', ''))),
899}
900
901VALUE_ENUMS = {
902 'AccessQualifier': {'ReadOnly': (0, ()), 'WriteOnly': (1, ()), 'ReadWrite': (2, ())},
903 'AddressingModel': {'Logical': (0, ()), 'Physical32': (1, ()), 'Physical64': (2, ()), 'PhysicalStorageBuffer64': (5348, ()), 'PhysicalStorageBuffer64EXT': (5348, ())},
904 'BuiltIn': {'Position': (0, ()), 'PointSize': (1, ()), 'ClipDistance': (3, ()), 'CullDistance': (4, ()), 'VertexId': (5, ()), 'InstanceId': (6, ()), 'PrimitiveId': (7, ()), 'InvocationId': (8, ()), 'Layer': (9, ()), 'ViewportIndex': (10, ()), 'TessLevelOuter': (11, ()), 'TessLevelInner': (12, ()), 'TessCoord': (13, ()), 'PatchVertices': (14, ()), 'FragCoord': (15, ()), 'PointCoord': (16, ()), 'FrontFacing': (17, ()), 'SampleId': (18, ()), 'SamplePosition': (19, ()), 'SampleMask': (20, ()), 'FragDepth': (22, ()), 'HelperInvocation': (23, ()), 'NumWorkgroups': (24, ()), 'WorkgroupSize': (25, ()), 'WorkgroupId': (26, ()), 'LocalInvocationId': (27, ()), 'GlobalInvocationId': (28, ()), 'LocalInvocationIndex': (29, ()), 'WorkDim': (30, ()), 'GlobalSize': (31, ()), 'EnqueuedWorkgroupSize': (32, ()), 'GlobalOffset': (33, ()), 'GlobalLinearId': (34, ()), 'SubgroupSize': (36, ()), 'SubgroupMaxSize': (37, ()), 'NumSubgroups': (38, ()), 'NumEnqueuedSubgroups': (39, ()), 'SubgroupId': (40, ()), 'SubgroupLocalInvocationId': (41, ()), 'VertexIndex': (42, ()), 'InstanceIndex': (43, ()), 'CoreIDARM': (4160, ()), 'CoreCountARM': (4161, ()), 'CoreMaxIDARM': (4162, ()), 'WarpIDARM': (4163, ()), 'WarpMaxIDARM': (4164, ()), 'SubgroupEqMask': (4416, ()), 'SubgroupEqMaskKHR': (4416, ()), 'SubgroupGeMask': (4417, ()), 'SubgroupGeMaskKHR': (4417, ()), 'SubgroupGtMask': (4418, ()), 'SubgroupGtMaskKHR': (4418, ()), 'SubgroupLeMask': (4419, ()), 'SubgroupLeMaskKHR': (4419, ()), 'SubgroupLtMask': (4420, ()), 'SubgroupLtMaskKHR': (4420, ()), 'BaseVertex': (4424, ()), 'BaseInstance': (4425, ()), 'DrawIndex': (4426, ()), 'PrimitiveShadingRateKHR': (4432, ()), 'DeviceIndex': (4438, ()), 'ViewIndex': (4440, ()), 'ShadingRateKHR': (4444, ()), 'TileOffsetQCOM': (4492, ()), 'TileDimensionQCOM': (4493, ()), 'TileApronSizeQCOM': (4494, ()), 'BaryCoordNoPerspAMD': (4992, ()), 'BaryCoordNoPerspCentroidAMD': (4993, ()), 'BaryCoordNoPerspSampleAMD': (4994, ()), 'BaryCoordSmoothAMD': (4995, ()), 'BaryCoordSmoothCentroidAMD': (4996, ()), 'BaryCoordSmoothSampleAMD': (4997, ()), 'BaryCoordPullModelAMD': (4998, ()), 'FragStencilRefEXT': (5014, ()), 'RemainingRecursionLevelsAMDX': (5021, ()), 'ShaderIndexAMDX': (5073, ()), 'SamplerHeapEXT': (5122, ()), 'ResourceHeapEXT': (5123, ()), 'HitInstanceLevelAMDX': (5190, ()), 'ViewportMaskNV': (5253, ()), 'SecondaryPositionNV': (5257, ()), 'SecondaryViewportMaskNV': (5258, ()), 'PositionPerViewNV': (5261, ()), 'ViewportMaskPerViewNV': (5262, ()), 'FullyCoveredEXT': (5264, ()), 'TaskCountNV': (5274, ()), 'PrimitiveCountNV': (5275, ()), 'PrimitiveIndicesNV': (5276, ()), 'ClipDistancePerViewNV': (5277, ()), 'CullDistancePerViewNV': (5278, ()), 'LayerPerViewNV': (5279, ()), 'MeshViewCountNV': (5280, ()), 'MeshViewIndicesNV': (5281, ()), 'BaryCoordKHR': (5286, ()), 'BaryCoordNV': (5286, ()), 'BaryCoordNoPerspKHR': (5287, ()), 'BaryCoordNoPerspNV': (5287, ()), 'FragSizeEXT': (5292, ()), 'FragmentSizeNV': (5292, ()), 'FragInvocationCountEXT': (5293, ()), 'InvocationsPerPixelNV': (5293, ()), 'PrimitivePointIndicesEXT': (5294, ()), 'PrimitiveLineIndicesEXT': (5295, ()), 'PrimitiveTriangleIndicesEXT': (5296, ()), 'CullPrimitiveEXT': (5299, ()), 'LaunchIdKHR': (5319, ()), 'LaunchIdNV': (5319, ()), 'LaunchSizeKHR': (5320, ()), 'LaunchSizeNV': (5320, ()), 'WorldRayOriginKHR': (5321, ()), 'WorldRayOriginNV': (5321, ()), 'WorldRayDirectionKHR': (5322, ()), 'WorldRayDirectionNV': (5322, ()), 'ObjectRayOriginKHR': (5323, ()), 'ObjectRayOriginNV': (5323, ()), 'ObjectRayDirectionKHR': (5324, ()), 'ObjectRayDirectionNV': (5324, ()), 'RayTminKHR': (5325, ()), 'RayTminNV': (5325, ()), 'RayTmaxKHR': (5326, ()), 'RayTmaxNV': (5326, ()), 'InstanceCustomIndexKHR': (5327, ()), 'InstanceCustomIndexNV': (5327, ()), 'ObjectToWorldKHR': (5330, ()), 'ObjectToWorldNV': (5330, ()), 'WorldToObjectKHR': (5331, ()), 'WorldToObjectNV': (5331, ()), 'HitTNV': (5332, ()), 'HitKindKHR': (5333, ()), 'HitKindNV': (5333, ()), 'CurrentRayTimeNV': (5334, ()), 'HitTriangleVertexPositionsKHR': (5335, ()), 'HitMicroTriangleVertexPositionsNV': (5337, ()), 'HitMicroTriangleVertexBarycentricsNV': (5344, ()), 'IncomingRayFlagsKHR': (5351, ()), 'IncomingRayFlagsNV': (5351, ()), 'RayGeometryIndexKHR': (5352, ()), 'HitIsSphereNV': (5359, ()), 'HitIsLSSNV': (5360, ()), 'HitSpherePositionNV': (5361, ()), 'WarpsPerSMNV': (5374, ()), 'SMCountNV': (5375, ()), 'WarpIDNV': (5376, ()), 'SMIDNV': (5377, ()), 'HitLSSPositionsNV': (5396, ()), 'HitKindFrontFacingMicroTriangleNV': (5405, ()), 'HitKindBackFacingMicroTriangleNV': (5406, ()), 'HitSphereRadiusNV': (5420, ()), 'HitLSSRadiiNV': (5421, ()), 'ClusterIDNV': (5436, ()), 'CullMaskKHR': (6021, ()), 'DeviceBarrierExecutionValidINTEL': (6186, ()), 'DeviceBarrierValidINTEL': (6186, ())},
905 'Capability': {'Matrix': (0, ()), 'Shader': (1, ()), 'Geometry': (2, ()), 'Tessellation': (3, ()), 'Addresses': (4, ()), 'Linkage': (5, ()), 'Kernel': (6, ()), 'Vector16': (7, ()), 'Float16Buffer': (8, ()), 'Float16': (9, ()), 'Float64': (10, ()), 'Int64': (11, ()), 'Int64Atomics': (12, ()), 'ImageBasic': (13, ()), 'ImageReadWrite': (14, ()), 'ImageMipmap': (15, ()), 'Pipes': (17, ()), 'Groups': (18, ()), 'DeviceEnqueue': (19, ()), 'LiteralSampler': (20, ()), 'AtomicStorage': (21, ()), 'Int16': (22, ()), 'TessellationPointSize': (23, ()), 'GeometryPointSize': (24, ()), 'ImageGatherExtended': (25, ()), 'StorageImageMultisample': (27, ()), 'UniformBufferArrayDynamicIndexing': (28, ()), 'SampledImageArrayDynamicIndexing': (29, ()), 'StorageBufferArrayDynamicIndexing': (30, ()), 'StorageImageArrayDynamicIndexing': (31, ()), 'ClipDistance': (32, ()), 'CullDistance': (33, ()), 'ImageCubeArray': (34, ()), 'SampleRateShading': (35, ()), 'ImageRect': (36, ()), 'SampledRect': (37, ()), 'GenericPointer': (38, ()), 'Int8': (39, ()), 'InputAttachment': (40, ()), 'SparseResidency': (41, ()), 'MinLod': (42, ()), 'Sampled1D': (43, ()), 'Image1D': (44, ()), 'SampledCubeArray': (45, ()), 'SampledBuffer': (46, ()), 'ImageBuffer': (47, ()), 'ImageMSArray': (48, ()), 'StorageImageExtendedFormats': (49, ()), 'ImageQuery': (50, ()), 'DerivativeControl': (51, ()), 'InterpolationFunction': (52, ()), 'TransformFeedback': (53, ()), 'GeometryStreams': (54, ()), 'StorageImageReadWithoutFormat': (55, ()), 'StorageImageWriteWithoutFormat': (56, ()), 'MultiViewport': (57, ()), 'SubgroupDispatch': (58, ()), 'NamedBarrier': (59, ()), 'PipeStorage': (60, ()), 'GroupNonUniform': (61, ()), 'GroupNonUniformVote': (62, ()), 'GroupNonUniformArithmetic': (63, ()), 'GroupNonUniformBallot': (64, ()), 'GroupNonUniformShuffle': (65, ()), 'GroupNonUniformShuffleRelative': (66, ()), 'GroupNonUniformClustered': (67, ()), 'GroupNonUniformQuad': (68, ()), 'ShaderLayer': (69, ()), 'ShaderViewportIndex': (70, ()), 'UniformDecoration': (71, ()), 'CoreBuiltinsARM': (4165, ()), 'TileImageColorReadAccessEXT': (4166, ()), 'TileImageDepthReadAccessEXT': (4167, ()), 'TileImageStencilReadAccessEXT': (4168, ()), 'TensorsARM': (4174, ()), 'StorageTensorArrayDynamicIndexingARM': (4175, ()), 'StorageTensorArrayNonUniformIndexingARM': (4176, ()), 'GraphARM': (4191, ()), 'CooperativeMatrixLayoutsARM': (4201, ()), 'Float8EXT': (4212, ()), 'Float8CooperativeMatrixEXT': (4213, ()), 'Float6EXT': (4228, ()), 'Float4EXT': (4229, ()), 'Float8UnsignedE8M0EXT': (4230, ()), 'MXInt8EXT': (4231, ()), 'BitcastExtractEXT': (4232, ()), 'FragmentShadingRateKHR': (4422, ()), 'SubgroupBallotKHR': (4423, ()), 'DrawParameters': (4427, ()), 'WorkgroupMemoryExplicitLayoutKHR': (4428, ()), 'WorkgroupMemoryExplicitLayout8BitAccessKHR': (4429, ()), 'WorkgroupMemoryExplicitLayout16BitAccessKHR': (4430, ()), 'SubgroupVoteKHR': (4431, ()), 'StorageBuffer16BitAccess': (4433, ()), 'StorageUniformBufferBlock16': (4433, ()), 'UniformAndStorageBuffer16BitAccess': (4434, ()), 'StorageUniform16': (4434, ()), 'StoragePushConstant16': (4435, ()), 'StorageInputOutput16': (4436, ()), 'DeviceGroup': (4437, ()), 'MultiView': (4439, ()), 'VariablePointersStorageBuffer': (4441, ()), 'VariablePointers': (4442, ()), 'AtomicStorageOps': (4445, ()), 'SampleMaskPostDepthCoverage': (4447, ()), 'StorageBuffer8BitAccess': (4448, ()), 'UniformAndStorageBuffer8BitAccess': (4449, ()), 'StoragePushConstant8': (4450, ()), 'DenormPreserve': (4464, ()), 'DenormFlushToZero': (4465, ()), 'SignedZeroInfNanPreserve': (4466, ()), 'RoundingModeRTE': (4467, ()), 'RoundingModeRTZ': (4468, ()), 'RayQueryProvisionalKHR': (4471, ()), 'RayQueryKHR': (4472, ()), 'UntypedPointersKHR': (4473, ()), 'RayTraversalPrimitiveCullingKHR': (4478, ()), 'RayTracingKHR': (4479, ()), 'TextureSampleWeightedQCOM': (4484, ()), 'TextureBoxFilterQCOM': (4485, ()), 'TextureBlockMatchQCOM': (4486, ()), 'TileShadingQCOM': (4495, ()), 'CooperativeMatrixConversionQCOM': (4496, ()), 'TextureBlockMatch2QCOM': (4498, ()), 'BFloat16MulAddQCOM': (4504, ()), 'SubgroupSizeQCOM': (4506, ()), 'MultipleWaitQueuesQCOM': (4539, ()), 'ImageGatherLinearQCOM': (4543, ()), 'ImageGatherExtendedModesQCOM': (4544, ()), 'Float16ImageAMD': (5008, ()), 'ImageGatherBiasLodAMD': (5009, ()), 'FragmentMaskAMD': (5010, ()), 'StencilExportEXT': (5013, ()), 'ImageReadWriteLodAMD': (5015, ()), 'Int64ImageEXT': (5016, ()), 'ShaderClockKHR': (5055, ()), 'ShaderEnqueueAMDX': (5067, ()), 'QuadControlKHR': (5087, ()), 'Int4TypeINTEL': (5112, ()), 'Int4CooperativeMatrixINTEL': (5114, ()), 'BFloat16TypeKHR': (5116, ()), 'BFloat16DotProductKHR': (5117, ()), 'BFloat16CooperativeMatrixKHR': (5118, ()), 'AbortKHR': (5120, ()), 'DescriptorHeapEXT': (5128, ()), 'ConstantDataKHR': (5146, ()), 'PoisonFreezeKHR': (5156, ()), 'WeakLinkageAMD': (5181, ()), 'RayTracingMultiLevelAccelerationStructureAMDX': (5191, ()), 'RayQueryMultiLevelAccelerationStructureAMDX': (5192, ()), 'SampleMaskOverrideCoverageNV': (5249, ()), 'GeometryShaderPassthroughNV': (5251, ()), 'ShaderViewportIndexLayerEXT': (5254, ()), 'ShaderViewportIndexLayerNV': (5254, ()), 'ShaderViewportMaskNV': (5255, ()), 'ShaderStereoViewNV': (5259, ()), 'PerViewAttributesNV': (5260, ()), 'FragmentFullyCoveredEXT': (5265, ()), 'MeshShadingNV': (5266, ()), 'ImageFootprintNV': (5282, ()), 'MeshShadingEXT': (5283, ()), 'FragmentBarycentricKHR': (5284, ()), 'FragmentBarycentricNV': (5284, ()), 'ComputeDerivativeGroupQuadsKHR': (5288, ()), 'ComputeDerivativeGroupQuadsNV': (5288, ()), 'FragmentDensityEXT': (5291, ()), 'ShadingRateNV': (5291, ()), 'GroupNonUniformPartitionedEXT': (5297, ()), 'GroupNonUniformPartitionedNV': (5297, ()), 'ShaderNonUniform': (5301, ()), 'ShaderNonUniformEXT': (5301, ()), 'RuntimeDescriptorArray': (5302, ()), 'RuntimeDescriptorArrayEXT': (5302, ()), 'InputAttachmentArrayDynamicIndexing': (5303, ()), 'InputAttachmentArrayDynamicIndexingEXT': (5303, ()), 'UniformTexelBufferArrayDynamicIndexing': (5304, ()), 'UniformTexelBufferArrayDynamicIndexingEXT': (5304, ()), 'StorageTexelBufferArrayDynamicIndexing': (5305, ()), 'StorageTexelBufferArrayDynamicIndexingEXT': (5305, ()), 'UniformBufferArrayNonUniformIndexing': (5306, ()), 'UniformBufferArrayNonUniformIndexingEXT': (5306, ()), 'SampledImageArrayNonUniformIndexing': (5307, ()), 'SampledImageArrayNonUniformIndexingEXT': (5307, ()), 'StorageBufferArrayNonUniformIndexing': (5308, ()), 'StorageBufferArrayNonUniformIndexingEXT': (5308, ()), 'StorageImageArrayNonUniformIndexing': (5309, ()), 'StorageImageArrayNonUniformIndexingEXT': (5309, ()), 'InputAttachmentArrayNonUniformIndexing': (5310, ()), 'InputAttachmentArrayNonUniformIndexingEXT': (5310, ()), 'UniformTexelBufferArrayNonUniformIndexing': (5311, ()), 'UniformTexelBufferArrayNonUniformIndexingEXT': (5311, ()), 'StorageTexelBufferArrayNonUniformIndexing': (5312, ()), 'StorageTexelBufferArrayNonUniformIndexingEXT': (5312, ()), 'RayTracingPositionFetchKHR': (5336, ()), 'RayTracingNV': (5340, ()), 'RayTracingMotionBlurNV': (5341, ()), 'VulkanMemoryModel': (5345, ()), 'VulkanMemoryModelKHR': (5345, ()), 'VulkanMemoryModelDeviceScope': (5346, ()), 'VulkanMemoryModelDeviceScopeKHR': (5346, ()), 'PhysicalStorageBufferAddresses': (5347, ()), 'PhysicalStorageBufferAddressesEXT': (5347, ()), 'ComputeDerivativeGroupLinearKHR': (5350, ()), 'ComputeDerivativeGroupLinearNV': (5350, ()), 'RayTracingProvisionalKHR': (5353, ()), 'CooperativeMatrixNV': (5357, ()), 'FragmentShaderSampleInterlockEXT': (5363, ()), 'FragmentShaderShadingRateInterlockEXT': (5372, ()), 'ShaderSMBuiltinsNV': (5373, ()), 'FragmentShaderPixelInterlockEXT': (5378, ()), 'DemoteToHelperInvocation': (5379, ()), 'DemoteToHelperInvocationEXT': (5379, ()), 'DisplacementMicromapNV': (5380, ()), 'RayTracingOpacityMicromapKHR': (5381, ()), 'RayTracingOpacityMicromapEXT': (5381, ()), 'ShaderInvocationReorderNV': (5383, ()), 'ShaderInvocationReorderEXT': (5388, ()), 'BindlessTextureNV': (5390, ()), 'RayQueryPositionFetchKHR': (5391, ()), 'CooperativeVectorNV': (5394, ()), 'AtomicFloat16VectorNV': (5404, ()), 'RayTracingDisplacementMicromapNV': (5409, ()), 'RawAccessChainsNV': (5414, ()), 'RayTracingSpheresGeometryNV': (5418, ()), 'RayTracingLinearSweptSpheresGeometryNV': (5419, ()), 'PushConstantBanksNV': (5423, ()), 'LongVectorEXT': (5425, ()), 'Shader64BitIndexingEXT': (5426, ()), 'CooperativeMatrixConversionsEXT': (5429, ()), 'CooperativeMatrixReductionsEXT': (5430, ()), 'CooperativeMatrixReductionsNV': (5430, ()), 'CooperativeMatrixConversionsNV': (5431, ()), 'CooperativeMatrixPerElementOperationsEXT': (5432, ()), 'CooperativeMatrixPerElementOperationsNV': (5432, ()), 'CooperativeMatrixTensorAddressingNV': (5433, ()), 'CooperativeMatrixBlockLoadsNV': (5434, ()), 'CooperativeVectorTrainingNV': (5435, ()), 'RayTracingClusterAccelerationStructureNV': (5437, ()), 'CooperativeMatrixGetCoordinateEXT': (5438, ()), 'TensorAddressingNV': (5439, ()), 'CooperativeMatrixDecodeVectorNV': (5447, ()), 'SubgroupShuffleINTEL': (5568, ()), 'SubgroupBufferBlockIOINTEL': (5569, ()), 'SubgroupImageBlockIOINTEL': (5570, ()), 'SubgroupImageMediaBlockIOINTEL': (5579, ()), 'RoundToInfinityINTEL': (5582, ()), 'FloatingPointModeINTEL': (5583, ()), 'IntegerFunctions2INTEL': (5584, ()), 'FunctionPointersINTEL': (5603, ()), 'IndirectReferencesINTEL': (5604, ()), 'AsmINTEL': (5606, ()), 'AtomicFloat32MinMaxEXT': (5612, ()), 'AtomicFloat64MinMaxEXT': (5613, ()), 'AtomicFloat16MinMaxEXT': (5616, ()), 'VectorComputeINTEL': (5617, ()), 'VectorAnyINTEL': (5619, ()), 'ExpectAssumeKHR': (5629, ()), 'SubgroupAvcMotionEstimationINTEL': (5696, ()), 'SubgroupAvcMotionEstimationIntraINTEL': (5697, ()), 'SubgroupAvcMotionEstimationChromaINTEL': (5698, ()), 'VariableLengthArrayINTEL': (5817, ()), 'FunctionFloatControlINTEL': (5821, ()), 'FPGAMemoryAttributesALTERA': (5824, ()), 'FPGAMemoryAttributesINTEL': (5824, ()), 'FPFastMathModeINTEL': (5837, ()), 'ArbitraryPrecisionIntegersALTERA': (5844, ()), 'ArbitraryPrecisionIntegersINTEL': (5844, ()), 'ArbitraryPrecisionFloatingPointALTERA': (5845, ()), 'ArbitraryPrecisionFloatingPointINTEL': (5845, ()), 'UnstructuredLoopControlsINTEL': (5886, ()), 'FPGALoopControlsALTERA': (5888, ()), 'FPGALoopControlsINTEL': (5888, ()), 'KernelAttributesINTEL': (5892, ()), 'FPGAKernelAttributesINTEL': (5897, ()), 'FPGAMemoryAccessesALTERA': (5898, ()), 'FPGAMemoryAccessesINTEL': (5898, ()), 'FPGAClusterAttributesALTERA': (5904, ()), 'FPGAClusterAttributesINTEL': (5904, ()), 'LoopFuseALTERA': (5906, ()), 'LoopFuseINTEL': (5906, ()), 'FPGADSPControlALTERA': (5908, ()), 'FPGADSPControlINTEL': (5908, ()), 'MemoryAccessAliasingINTEL': (5910, ()), 'FPGAInvocationPipeliningAttributesALTERA': (5916, ()), 'FPGAInvocationPipeliningAttributesINTEL': (5916, ()), 'FPGABufferLocationALTERA': (5920, ()), 'FPGABufferLocationINTEL': (5920, ()), 'ArbitraryPrecisionFixedPointALTERA': (5922, ()), 'ArbitraryPrecisionFixedPointINTEL': (5922, ()), 'USMStorageClassesALTERA': (5935, ()), 'USMStorageClassesINTEL': (5935, ()), 'RuntimeAlignedAttributeALTERA': (5939, ()), 'RuntimeAlignedAttributeINTEL': (5939, ()), 'IOPipesALTERA': (5943, ()), 'IOPipesINTEL': (5943, ()), 'BlockingPipesALTERA': (5945, ()), 'BlockingPipesINTEL': (5945, ()), 'FPGARegALTERA': (5948, ()), 'FPGARegINTEL': (5948, ()), 'DotProductInputAll': (6016, ()), 'DotProductInputAllKHR': (6016, ()), 'DotProductInput4x8Bit': (6017, ()), 'DotProductInput4x8BitKHR': (6017, ()), 'DotProductInput4x8BitPacked': (6018, ()), 'DotProductInput4x8BitPackedKHR': (6018, ()), 'DotProduct': (6019, ()), 'DotProductKHR': (6019, ()), 'RayCullMaskKHR': (6020, ()), 'CooperativeMatrixKHR': (6022, ()), 'ReplicatedCompositesEXT': (6024, ()), 'BitInstructions': (6025, ()), 'GroupNonUniformRotateKHR': (6026, ()), 'FloatControls2': (6029, ()), 'FMAKHR': (6030, ()), 'RayTracingOpacityMicromapExecutionModeKHR': (6032, ()), 'AtomicFloat32AddEXT': (6033, ()), 'AtomicFloat64AddEXT': (6034, ()), 'LongCompositesINTEL': (6089, ()), 'OptNoneEXT': (6094, ()), 'OptNoneINTEL': (6094, ()), 'AtomicFloat16AddEXT': (6095, ()), 'DebugInfoModuleINTEL': (6114, ()), 'BFloat16ConversionINTEL': (6115, ()), 'SplitBarrierEXT': (6141, ()), 'SplitBarrierINTEL': (6141, ()), 'ArithmeticFenceEXT': (6144, ()), 'FPGAClusterAttributesV2ALTERA': (6150, ()), 'FPGAClusterAttributesV2INTEL': (6150, ()), 'FPGAKernelAttributesv2INTEL': (6161, ()), 'TaskSequenceALTERA': (6162, ()), 'TaskSequenceINTEL': (6162, ()), 'FPMaxErrorINTEL': (6169, ()), 'FPGALatencyControlALTERA': (6171, ()), 'FPGALatencyControlINTEL': (6171, ()), 'FPGAArgumentInterfacesALTERA': (6174, ()), 'FPGAArgumentInterfacesINTEL': (6174, ()), 'DeviceBarrierINTEL': (6185, ()), 'GlobalVariableHostAccessINTEL': (6187, ()), 'GlobalVariableFPGADecorationsALTERA': (6189, ()), 'GlobalVariableFPGADecorationsINTEL': (6189, ()), 'SubgroupBitcastShuffleINTEL': (6207, ()), 'FloatConversionsFToFINTEL': (6215, ()), 'FloatConversionsFToSINTEL': (6216, ()), 'SubgroupBufferPrefetchINTEL': (6220, ()), 'BFloat16ArithmeticEXT': (6226, ()), 'Subgroup2DBlockIOINTEL': (6228, ()), 'Subgroup2DBlockTransformINTEL': (6229, ()), 'Subgroup2DBlockTransposeINTEL': (6230, ()), 'SubgroupMatrixMultiplyAccumulateINTEL': (6236, ()), 'TernaryBitwiseFunctionINTEL': (6241, ()), 'UntypedVariableLengthArrayINTEL': (6243, ()), 'SpecConditionalINTEL': (6245, ()), 'FunctionVariantsINTEL': (6246, ()), 'AtomicBFloat16AddINTEL': (6255, ()), 'AtomicBFloat16MinMaxINTEL': (6256, ()), 'PredicatedIOINTEL': (6257, ()), 'AtomicInt16CompareExchangeINTEL': (6260, ()), 'Int16AtomicsINTEL': (6261, ()), 'AtomicBFloat16LoadStoreINTEL': (6262, ()), 'RoundedDivideSqrtINTEL': (6265, ()), 'PauseINTEL': (6266, ()), 'GroupUniformArithmeticKHR': (6400, ()), 'TensorFloat32RoundingINTEL': (6425, ()), 'MaskedGatherScatterINTEL': (6427, ()), 'CacheControlsINTEL': (6441, ()), 'RegisterLimitsINTEL': (6460, ()), 'BindlessImagesINTEL': (6528, ()), 'DotProductFloat16AccFloat32VALVE': (6912, ()), 'DotProductFloat16AccFloat16VALVE': (6913, ()), 'DotProductBFloat16AccVALVE': (6914, ()), 'DotProductFloat8AccFloat32VALVE': (6915, ()), 'IntrinsicSAMSUNG': (7041, ())},
906 'ComponentType': {'Float16NV': (0, ()), 'Float32NV': (1, ()), 'Float64NV': (2, ()), 'SignedInt8NV': (3, ()), 'SignedInt16NV': (4, ()), 'SignedInt32NV': (5, ()), 'SignedInt64NV': (6, ()), 'UnsignedInt8NV': (7, ()), 'UnsignedInt16NV': (8, ()), 'UnsignedInt32NV': (9, ()), 'UnsignedInt64NV': (10, ()), 'SignedInt8PackedNV': (1000491000, ()), 'UnsignedInt8PackedNV': (1000491001, ()), 'FloatE4M3NV': (1000491002, ()), 'FloatE5M2NV': (1000491003, ())},
907 'CooperativeMatrixLayout': {'RowMajorKHR': (0, ()), 'ColumnMajorKHR': (1, ()), 'RowBlockedInterleavedARM': (4202, ()), 'ColumnBlockedInterleavedARM': (4203, ())},
908 'CooperativeMatrixUse': {'MatrixAKHR': (0, ()), 'MatrixBKHR': (1, ()), 'MatrixAccumulatorKHR': (2, ())},
909 'CooperativeVectorMatrixLayout': {'RowMajorNV': (0, ()), 'ColumnMajorNV': (1, ()), 'InferencingOptimalNV': (2, ()), 'TrainingOptimalNV': (3, ())},
910 'Decoration': {'RelaxedPrecision': (0, ()), 'SpecId': (1, ('LiteralInteger',)), 'Block': (2, ()), 'BufferBlock': (3, ()), 'RowMajor': (4, ()), 'ColMajor': (5, ()), 'ArrayStride': (6, ('LiteralInteger',)), 'MatrixStride': (7, ('LiteralInteger',)), 'GLSLShared': (8, ()), 'GLSLPacked': (9, ()), 'CPacked': (10, ()), 'BuiltIn': (11, ('BuiltIn',)), 'NoPerspective': (13, ()), 'Flat': (14, ()), 'Patch': (15, ()), 'Centroid': (16, ()), 'Sample': (17, ()), 'Invariant': (18, ()), 'Restrict': (19, ()), 'Aliased': (20, ()), 'Volatile': (21, ()), 'Constant': (22, ()), 'Coherent': (23, ()), 'NonWritable': (24, ()), 'NonReadable': (25, ()), 'Uniform': (26, ()), 'UniformId': (27, ('IdScope',)), 'SaturatedConversion': (28, ()), 'Stream': (29, ('LiteralInteger',)), 'Location': (30, ('LiteralInteger',)), 'Component': (31, ('LiteralInteger',)), 'Index': (32, ('LiteralInteger',)), 'Binding': (33, ('LiteralInteger',)), 'DescriptorSet': (34, ('LiteralInteger',)), 'Offset': (35, ('LiteralInteger',)), 'XfbBuffer': (36, ('LiteralInteger',)), 'XfbStride': (37, ('LiteralInteger',)), 'FuncParamAttr': (38, ('FunctionParameterAttribute',)), 'FPRoundingMode': (39, ('FPRoundingMode',)), 'FPFastMathMode': (40, ('FPFastMathMode',)), 'LinkageAttributes': (41, ('LiteralString', 'LinkageType')), 'NoContraction': (42, ()), 'InputAttachmentIndex': (43, ('LiteralInteger',)), 'Alignment': (44, ('LiteralInteger',)), 'MaxByteOffset': (45, ('LiteralInteger',)), 'AlignmentId': (46, ('IdRef',)), 'MaxByteOffsetId': (47, ('IdRef',)), 'SaturatedToLargestFloat8NormalConversionEXT': (4216, ()), 'NoSignedWrap': (4469, ()), 'NoUnsignedWrap': (4470, ()), 'WeightTextureQCOM': (4487, ()), 'BlockMatchTextureQCOM': (4488, ()), 'BlockMatchSamplerQCOM': (4499, ()), 'ExplicitInterpAMD': (4999, ()), 'NodeSharesPayloadLimitsWithAMDX': (5019, ('IdRef',)), 'NodeMaxPayloadsAMDX': (5020, ('IdRef',)), 'TrackFinishWritingAMDX': (5078, ()), 'PayloadNodeNameAMDX': (5091, ('IdRef',)), 'PayloadNodeBaseIndexAMDX': (5098, ('IdRef',)), 'PayloadNodeSparseArrayAMDX': (5099, ()), 'PayloadNodeArraySizeAMDX': (5100, ('IdRef',)), 'PayloadDispatchIndirectAMDX': (5105, ()), 'ArrayStrideIdEXT': (5124, ('IdRef',)), 'OffsetIdEXT': (5125, ('IdRef',)), 'UTFEncodedKHR': (5145, ()), 'OverrideCoverageNV': (5248, ()), 'PassthroughNV': (5250, ()), 'ViewportRelativeNV': (5252, ()), 'SecondaryViewportRelativeNV': (5256, ('LiteralInteger',)), 'PerPrimitiveEXT': (5271, ()), 'PerPrimitiveNV': (5271, ()), 'PerViewNV': (5272, ()), 'PerTaskNV': (5273, ()), 'PerVertexKHR': (5285, ()), 'PerVertexNV': (5285, ()), 'NonUniform': (5300, ()), 'NonUniformEXT': (5300, ()), 'RestrictPointer': (5355, ()), 'RestrictPointerEXT': (5355, ()), 'AliasedPointer': (5356, ()), 'AliasedPointerEXT': (5356, ()), 'MemberOffsetNV': (5358, ('LiteralInteger',)), 'HitObjectShaderRecordBufferNV': (5386, ()), 'HitObjectShaderRecordBufferEXT': (5389, ()), 'BankNV': (5397, ('LiteralInteger',)), 'BindlessSamplerNV': (5398, ()), 'BindlessImageNV': (5399, ()), 'BoundSamplerNV': (5400, ()), 'BoundImageNV': (5401, ()), 'CooperativeMatrixTransposeEXT': (5440, ()), 'SIMTCallINTEL': (5599, ('LiteralInteger',)), 'ReferencedIndirectlyINTEL': (5602, ()), 'ClobberINTEL': (5607, ('LiteralString',)), 'SideEffectsINTEL': (5608, ()), 'VectorComputeVariableINTEL': (5624, ()), 'FuncParamIOKindINTEL': (5625, ('LiteralInteger',)), 'VectorComputeFunctionINTEL': (5626, ()), 'StackCallINTEL': (5627, ()), 'GlobalVariableOffsetINTEL': (5628, ('LiteralInteger',)), 'CounterBuffer': (5634, ('IdRef',)), 'HlslCounterBufferGOOGLE': (5634, ('IdRef',)), 'UserSemantic': (5635, ('LiteralString',)), 'HlslSemanticGOOGLE': (5635, ('LiteralString',)), 'UserTypeGOOGLE': (5636, ('LiteralString',)), 'FunctionRoundingModeINTEL': (5822, ('LiteralInteger', 'FPRoundingMode')), 'FunctionDenormModeINTEL': (5823, ('LiteralInteger', 'FPDenormMode')), 'RegisterALTERA': (5825, ()), 'RegisterINTEL': (5825, ()), 'MemoryALTERA': (5826, ('LiteralString',)), 'MemoryINTEL': (5826, ('LiteralString',)), 'NumbanksALTERA': (5827, ('LiteralInteger',)), 'NumbanksINTEL': (5827, ('LiteralInteger',)), 'BankwidthALTERA': (5828, ('LiteralInteger',)), 'BankwidthINTEL': (5828, ('LiteralInteger',)), 'MaxPrivateCopiesALTERA': (5829, ('LiteralInteger',)), 'MaxPrivateCopiesINTEL': (5829, ('LiteralInteger',)), 'SinglepumpALTERA': (5830, ()), 'SinglepumpINTEL': (5830, ()), 'DoublepumpALTERA': (5831, ()), 'DoublepumpINTEL': (5831, ()), 'MaxReplicatesALTERA': (5832, ('LiteralInteger',)), 'MaxReplicatesINTEL': (5832, ('LiteralInteger',)), 'SimpleDualPortALTERA': (5833, ()), 'SimpleDualPortINTEL': (5833, ()), 'MergeALTERA': (5834, ('LiteralString', 'LiteralString')), 'MergeINTEL': (5834, ('LiteralString', 'LiteralString')), 'BankBitsALTERA': (5835, ('LiteralInteger',)), 'BankBitsINTEL': (5835, ('LiteralInteger',)), 'ForcePow2DepthALTERA': (5836, ('LiteralInteger',)), 'ForcePow2DepthINTEL': (5836, ('LiteralInteger',)), 'StridesizeALTERA': (5883, ('LiteralInteger',)), 'StridesizeINTEL': (5883, ('LiteralInteger',)), 'WordsizeALTERA': (5884, ('LiteralInteger',)), 'WordsizeINTEL': (5884, ('LiteralInteger',)), 'TrueDualPortALTERA': (5885, ()), 'TrueDualPortINTEL': (5885, ()), 'BurstCoalesceALTERA': (5899, ()), 'BurstCoalesceINTEL': (5899, ()), 'CacheSizeALTERA': (5900, ('LiteralInteger',)), 'CacheSizeINTEL': (5900, ('LiteralInteger',)), 'DontStaticallyCoalesceALTERA': (5901, ()), 'DontStaticallyCoalesceINTEL': (5901, ()), 'PrefetchALTERA': (5902, ('LiteralInteger',)), 'PrefetchINTEL': (5902, ('LiteralInteger',)), 'StallEnableALTERA': (5905, ()), 'StallEnableINTEL': (5905, ()), 'FuseLoopsInFunctionALTERA': (5907, ()), 'FuseLoopsInFunctionINTEL': (5907, ()), 'MathOpDSPModeALTERA': (5909, ('LiteralInteger', 'LiteralInteger')), 'MathOpDSPModeINTEL': (5909, ('LiteralInteger', 'LiteralInteger')), 'AliasScopeINTEL': (5914, ('IdRef',)), 'NoAliasINTEL': (5915, ('IdRef',)), 'InitiationIntervalALTERA': (5917, ('LiteralInteger',)), 'InitiationIntervalINTEL': (5917, ('LiteralInteger',)), 'MaxConcurrencyALTERA': (5918, ('LiteralInteger',)), 'MaxConcurrencyINTEL': (5918, ('LiteralInteger',)), 'PipelineEnableALTERA': (5919, ('LiteralInteger',)), 'PipelineEnableINTEL': (5919, ('LiteralInteger',)), 'BufferLocationALTERA': (5921, ('LiteralInteger',)), 'BufferLocationINTEL': (5921, ('LiteralInteger',)), 'IOPipeStorageALTERA': (5944, ('LiteralInteger',)), 'IOPipeStorageINTEL': (5944, ('LiteralInteger',)), 'FunctionFloatingPointModeINTEL': (6080, ('LiteralInteger', 'FPOperationMode')), 'SingleElementVectorINTEL': (6085, ()), 'VectorComputeCallableFunctionINTEL': (6087, ()), 'MediaBlockIOINTEL': (6140, ()), 'StallFreeALTERA': (6151, ()), 'StallFreeINTEL': (6151, ()), 'FPMaxErrorDecorationINTEL': (6170, ('LiteralFloat',)), 'LatencyControlLabelALTERA': (6172, ('LiteralInteger',)), 'LatencyControlLabelINTEL': (6172, ('LiteralInteger',)), 'LatencyControlConstraintALTERA': (6173, ('LiteralInteger', 'LiteralInteger', 'LiteralInteger')), 'LatencyControlConstraintINTEL': (6173, ('LiteralInteger', 'LiteralInteger', 'LiteralInteger')), 'ConduitKernelArgumentALTERA': (6175, ()), 'ConduitKernelArgumentINTEL': (6175, ()), 'RegisterMapKernelArgumentALTERA': (6176, ()), 'RegisterMapKernelArgumentINTEL': (6176, ()), 'MMHostInterfaceAddressWidthALTERA': (6177, ('LiteralInteger',)), 'MMHostInterfaceAddressWidthINTEL': (6177, ('LiteralInteger',)), 'MMHostInterfaceDataWidthALTERA': (6178, ('LiteralInteger',)), 'MMHostInterfaceDataWidthINTEL': (6178, ('LiteralInteger',)), 'MMHostInterfaceLatencyALTERA': (6179, ('LiteralInteger',)), 'MMHostInterfaceLatencyINTEL': (6179, ('LiteralInteger',)), 'MMHostInterfaceReadWriteModeALTERA': (6180, ('AccessQualifier',)), 'MMHostInterfaceReadWriteModeINTEL': (6180, ('AccessQualifier',)), 'MMHostInterfaceMaxBurstALTERA': (6181, ('LiteralInteger',)), 'MMHostInterfaceMaxBurstINTEL': (6181, ('LiteralInteger',)), 'MMHostInterfaceWaitRequestALTERA': (6182, ('LiteralInteger',)), 'MMHostInterfaceWaitRequestINTEL': (6182, ('LiteralInteger',)), 'StableKernelArgumentALTERA': (6183, ()), 'StableKernelArgumentINTEL': (6183, ()), 'HostAccessINTEL': (6188, ('HostAccessQualifier', 'LiteralString')), 'InitModeALTERA': (6190, ('InitializationModeQualifier',)), 'InitModeINTEL': (6190, ('InitializationModeQualifier',)), 'ImplementInRegisterMapALTERA': (6191, ('LiteralInteger',)), 'ImplementInRegisterMapINTEL': (6191, ('LiteralInteger',)), 'ConditionalINTEL': (6247, ('IdRef',)), 'CacheControlLoadINTEL': (6442, ('LiteralInteger', 'LoadCacheControl')), 'CacheControlStoreINTEL': (6443, ('LiteralInteger', 'StoreCacheControl')), 'IntrinsicSAMSUNG': (7040, ('LiteralInteger',))},
911 'Dim': {'1D': (0, ()), '2D': (1, ()), '3D': (2, ()), 'Cube': (3, ()), 'Rect': (4, ()), 'Buffer': (5, ()), 'SubpassData': (6, ()), 'TileImageDataEXT': (4173, ())},
912 'ExecutionMode': {'Invocations': (0, ('LiteralInteger',)), 'SpacingEqual': (1, ()), 'SpacingFractionalEven': (2, ()), 'SpacingFractionalOdd': (3, ()), 'VertexOrderCw': (4, ()), 'VertexOrderCcw': (5, ()), 'PixelCenterInteger': (6, ()), 'OriginUpperLeft': (7, ()), 'OriginLowerLeft': (8, ()), 'EarlyFragmentTests': (9, ()), 'PointMode': (10, ()), 'Xfb': (11, ()), 'DepthReplacing': (12, ()), 'DepthGreater': (14, ()), 'DepthLess': (15, ()), 'DepthUnchanged': (16, ()), 'LocalSize': (17, ('LiteralInteger', 'LiteralInteger', 'LiteralInteger')), 'LocalSizeHint': (18, ('LiteralInteger', 'LiteralInteger', 'LiteralInteger')), 'InputPoints': (19, ()), 'InputLines': (20, ()), 'InputLinesAdjacency': (21, ()), 'Triangles': (22, ()), 'InputTrianglesAdjacency': (23, ()), 'Quads': (24, ()), 'Isolines': (25, ()), 'OutputVertices': (26, ('LiteralInteger',)), 'OutputPoints': (27, ()), 'OutputLineStrip': (28, ()), 'OutputTriangleStrip': (29, ()), 'VecTypeHint': (30, ('LiteralInteger',)), 'ContractionOff': (31, ()), 'Initializer': (33, ()), 'Finalizer': (34, ()), 'SubgroupSize': (35, ('LiteralInteger',)), 'SubgroupsPerWorkgroup': (36, ('LiteralInteger',)), 'SubgroupsPerWorkgroupId': (37, ('IdRef',)), 'LocalSizeId': (38, ('IdRef', 'IdRef', 'IdRef')), 'LocalSizeHintId': (39, ('IdRef', 'IdRef', 'IdRef')), 'NonCoherentColorAttachmentReadEXT': (4169, ()), 'NonCoherentDepthAttachmentReadEXT': (4170, ()), 'NonCoherentStencilAttachmentReadEXT': (4171, ()), 'SubgroupUniformControlFlowKHR': (4421, ()), 'PostDepthCoverage': (4446, ()), 'DenormPreserve': (4459, ('LiteralInteger',)), 'DenormFlushToZero': (4460, ('LiteralInteger',)), 'SignedZeroInfNanPreserve': (4461, ('LiteralInteger',)), 'RoundingModeRTE': (4462, ('LiteralInteger',)), 'RoundingModeRTZ': (4463, ('LiteralInteger',)), 'NonCoherentTileAttachmentReadQCOM': (4489, ()), 'TileShadingRateQCOM': (4490, ('LiteralInteger', 'LiteralInteger', 'LiteralInteger')), 'SubgroupSizeHalfQCOM': (4507, ()), 'SubgroupSizeFullQCOM': (4508, ()), 'EarlyAndLateFragmentTestsAMD': (5017, ()), 'StencilRefReplacingEXT': (5027, ()), 'CoalescingAMDX': (5069, ()), 'IsApiEntryAMDX': (5070, ('IdRef',)), 'MaxNodeRecursionAMDX': (5071, ('IdRef',)), 'StaticNumWorkgroupsAMDX': (5072, ('IdRef', 'IdRef', 'IdRef')), 'ShaderIndexAMDX': (5073, ('IdRef',)), 'MaxNumWorkgroupsAMDX': (5077, ('IdRef', 'IdRef', 'IdRef')), 'StencilRefUnchangedFrontAMD': (5079, ()), 'StencilRefGreaterFrontAMD': (5080, ()), 'StencilRefLessFrontAMD': (5081, ()), 'StencilRefUnchangedBackAMD': (5082, ()), 'StencilRefGreaterBackAMD': (5083, ()), 'StencilRefLessBackAMD': (5084, ()), 'QuadDerivativesKHR': (5088, ()), 'RequireFullQuadsKHR': (5089, ()), 'SharesInputWithAMDX': (5102, ('IdRef', 'IdRef')), 'ArithmeticPoisonKHR': (5157, ()), 'OutputLinesEXT': (5269, ()), 'OutputLinesNV': (5269, ()), 'OutputPrimitivesEXT': (5270, ('LiteralInteger',)), 'OutputPrimitivesNV': (5270, ('LiteralInteger',)), 'DerivativeGroupQuadsKHR': (5289, ()), 'DerivativeGroupQuadsNV': (5289, ()), 'DerivativeGroupLinearKHR': (5290, ()), 'DerivativeGroupLinearNV': (5290, ()), 'OutputTrianglesEXT': (5298, ()), 'OutputTrianglesNV': (5298, ()), 'PixelInterlockOrderedEXT': (5366, ()), 'PixelInterlockUnorderedEXT': (5367, ()), 'SampleInterlockOrderedEXT': (5368, ()), 'SampleInterlockUnorderedEXT': (5369, ()), 'ShadingRateInterlockOrderedEXT': (5370, ()), 'ShadingRateInterlockUnorderedEXT': (5371, ()), 'Shader64BitIndexingEXT': (5427, ()), 'SharedLocalMemorySizeINTEL': (5618, ('LiteralInteger',)), 'RoundingModeRTPINTEL': (5620, ('LiteralInteger',)), 'RoundingModeRTNINTEL': (5621, ('LiteralInteger',)), 'FloatingPointModeALTINTEL': (5622, ('LiteralInteger',)), 'FloatingPointModeIEEEINTEL': (5623, ('LiteralInteger',)), 'MaxWorkgroupSizeINTEL': (5893, ('LiteralInteger', 'LiteralInteger', 'LiteralInteger')), 'MaxWorkDimINTEL': (5894, ('LiteralInteger',)), 'NoGlobalOffsetINTEL': (5895, ()), 'NumSIMDWorkitemsINTEL': (5896, ('LiteralInteger',)), 'SchedulerTargetFmaxMhzINTEL': (5903, ('LiteralInteger',)), 'MaximallyReconvergesKHR': (6023, ()), 'FPFastMathDefault': (6028, ('IdRef', 'IdRef')), 'OpacityMicromapIdKHR': (6031, ('IdRef',)), 'StreamingInterfaceINTEL': (6154, ('LiteralInteger',)), 'RegisterMapInterfaceINTEL': (6160, ('LiteralInteger',)), 'NamedBarrierCountINTEL': (6417, ('LiteralInteger',)), 'MaximumRegistersINTEL': (6461, ('LiteralInteger',)), 'MaximumRegistersIdINTEL': (6462, ('IdRef',)), 'NamedMaximumRegistersINTEL': (6463, ('NamedMaximumNumberOfRegisters',))},
913 'ExecutionModel': {'Vertex': (0, ()), 'TessellationControl': (1, ()), 'TessellationEvaluation': (2, ()), 'Geometry': (3, ()), 'Fragment': (4, ()), 'GLCompute': (5, ()), 'Kernel': (6, ()), 'TaskNV': (5267, ()), 'MeshNV': (5268, ()), 'RayGenerationKHR': (5313, ()), 'RayGenerationNV': (5313, ()), 'IntersectionKHR': (5314, ()), 'IntersectionNV': (5314, ()), 'AnyHitKHR': (5315, ()), 'AnyHitNV': (5315, ()), 'ClosestHitKHR': (5316, ()), 'ClosestHitNV': (5316, ()), 'MissKHR': (5317, ()), 'MissNV': (5317, ()), 'CallableKHR': (5318, ()), 'CallableNV': (5318, ()), 'TaskEXT': (5364, ()), 'MeshEXT': (5365, ())},
914 'FPDenormMode': {'Preserve': (0, ()), 'FlushToZero': (1, ())},
915 'FPEncoding': {'BFloat16KHR': (0, ()), 'Float8E4M3EXT': (4214, ()), 'Float8E5M2EXT': (4215, ()), 'Float6E2M3EXT': (4223, ()), 'Float6E3M2EXT': (4224, ()), 'Float4E2M1EXT': (4225, ()), 'Float8UnsignedE8M0EXT': (4226, ()), 'MXInt8EXT': (4227, ())},
916 'FPOperationMode': {'IEEE': (0, ()), 'ALT': (1, ())},
917 'FPRoundingMode': {'RTE': (0, ()), 'RTZ': (1, ()), 'RTP': (2, ()), 'RTN': (3, ())},
918 'FunctionParameterAttribute': {'Zext': (0, ()), 'Sext': (1, ()), 'ByVal': (2, ()), 'Sret': (3, ()), 'NoAlias': (4, ()), 'NoCapture': (5, ()), 'NoWrite': (6, ()), 'NoReadWrite': (7, ()), 'RuntimeAlignedALTERA': (5940, ()), 'RuntimeAlignedINTEL': (5940, ())},
919 'GatherModes': {'Gather4x1QCOM': (0, ()), 'GatherDQCOM': (1, ()), 'GatherH2QCOM': (2, ()), 'GatherV2QCOM': (3, ())},
920 'GroupOperation': {'Reduce': (0, ()), 'InclusiveScan': (1, ()), 'ExclusiveScan': (2, ()), 'ClusteredReduce': (3, ()), 'PartitionedReduceEXT': (6, ()), 'PartitionedReduceNV': (6, ()), 'PartitionedInclusiveScanEXT': (7, ()), 'PartitionedInclusiveScanNV': (7, ()), 'PartitionedExclusiveScanEXT': (8, ()), 'PartitionedExclusiveScanNV': (8, ())},
921 'HostAccessQualifier': {'NoneINTEL': (0, ()), 'ReadINTEL': (1, ()), 'WriteINTEL': (2, ()), 'ReadWriteINTEL': (3, ())},
922 'ImageChannelDataType': {'SnormInt8': (0, ()), 'SnormInt16': (1, ()), 'UnormInt8': (2, ()), 'UnormInt16': (3, ()), 'UnormShort565': (4, ()), 'UnormShort555': (5, ()), 'UnormInt101010': (6, ()), 'SignedInt8': (7, ()), 'SignedInt16': (8, ()), 'SignedInt32': (9, ()), 'UnsignedInt8': (10, ()), 'UnsignedInt16': (11, ()), 'UnsignedInt32': (12, ()), 'HalfFloat': (13, ()), 'Float': (14, ()), 'UnormInt24': (15, ()), 'UnormInt101010_2': (16, ()), 'UnormInt10X6EXT': (17, ()), 'UnsignedIntRaw10EXT': (19, ()), 'UnsignedIntRaw12EXT': (20, ()), 'UnormInt2_101010EXT': (21, ()), 'UnsignedInt10X6EXT': (22, ()), 'UnsignedInt12X4EXT': (23, ()), 'UnsignedInt14X2EXT': (24, ()), 'UnormInt12X4EXT': (25, ()), 'UnormInt14X2EXT': (26, ())},
923 'ImageChannelOrder': {'R': (0, ()), 'A': (1, ()), 'RG': (2, ()), 'RA': (3, ()), 'RGB': (4, ()), 'RGBA': (5, ()), 'BGRA': (6, ()), 'ARGB': (7, ()), 'Intensity': (8, ()), 'Luminance': (9, ()), 'Rx': (10, ()), 'RGx': (11, ()), 'RGBx': (12, ()), 'Depth': (13, ()), 'DepthStencil': (14, ()), 'sRGB': (15, ()), 'sRGBx': (16, ()), 'sRGBA': (17, ()), 'sBGRA': (18, ()), 'ABGR': (19, ())},
924 'ImageFormat': {'Unknown': (0, ()), 'Rgba32f': (1, ()), 'Rgba16f': (2, ()), 'R32f': (3, ()), 'Rgba8': (4, ()), 'Rgba8Snorm': (5, ()), 'Rg32f': (6, ()), 'Rg16f': (7, ()), 'R11fG11fB10f': (8, ()), 'R16f': (9, ()), 'Rgba16': (10, ()), 'Rgb10A2': (11, ()), 'Rg16': (12, ()), 'Rg8': (13, ()), 'R16': (14, ()), 'R8': (15, ()), 'Rgba16Snorm': (16, ()), 'Rg16Snorm': (17, ()), 'Rg8Snorm': (18, ()), 'R16Snorm': (19, ()), 'R8Snorm': (20, ()), 'Rgba32i': (21, ()), 'Rgba16i': (22, ()), 'Rgba8i': (23, ()), 'R32i': (24, ()), 'Rg32i': (25, ()), 'Rg16i': (26, ()), 'Rg8i': (27, ()), 'R16i': (28, ()), 'R8i': (29, ()), 'Rgba32ui': (30, ()), 'Rgba16ui': (31, ()), 'Rgba8ui': (32, ()), 'R32ui': (33, ()), 'Rgb10a2ui': (34, ()), 'Rg32ui': (35, ()), 'Rg16ui': (36, ()), 'Rg8ui': (37, ()), 'R16ui': (38, ()), 'R8ui': (39, ()), 'R64ui': (40, ()), 'R64i': (41, ())},
925 'InitializationModeQualifier': {'InitOnDeviceReprogramALTERA': (0, ()), 'InitOnDeviceReprogramINTEL': (0, ()), 'InitOnDeviceResetALTERA': (1, ()), 'InitOnDeviceResetINTEL': (1, ())},
926 'KernelEnqueueFlags': {'NoWait': (0, ()), 'WaitKernel': (1, ()), 'WaitWorkGroup': (2, ())},
927 'LinkageType': {'Export': (0, ()), 'Import': (1, ()), 'LinkOnceODR': (2, ()), 'WeakAMD': (3, ())},
928 'LoadCacheControl': {'UncachedINTEL': (0, ()), 'CachedINTEL': (1, ()), 'StreamingINTEL': (2, ()), 'InvalidateAfterReadINTEL': (3, ()), 'ConstCachedINTEL': (4, ())},
929 'MemoryModel': {'Simple': (0, ()), 'GLSL450': (1, ()), 'OpenCL': (2, ()), 'Vulkan': (3, ()), 'VulkanKHR': (3, ())},
930 'NamedMaximumNumberOfRegisters': {'AutoINTEL': (0, ())},
931 'OverflowModes': {'WRAP': (0, ()), 'SAT': (1, ()), 'SAT_ZERO': (2, ()), 'SAT_SYM': (3, ())},
932 'PackedVectorFormat': {'PackedVectorFormat4x8Bit': (0, ()), 'PackedVectorFormat4x8BitKHR': (0, ())},
933 'QuantizationModes': {'TRN': (0, ()), 'TRN_ZERO': (1, ()), 'RND': (2, ()), 'RND_ZERO': (3, ()), 'RND_INF': (4, ()), 'RND_MIN_INF': (5, ()), 'RND_CONV': (6, ()), 'RND_CONV_ODD': (7, ())},
934 'RayQueryCandidateIntersectionType': {'RayQueryCandidateIntersectionTriangleKHR': (0, ()), 'RayQueryCandidateIntersectionAABBKHR': (1, ())},
935 'RayQueryCommittedIntersectionType': {'RayQueryCommittedIntersectionNoneKHR': (0, ()), 'RayQueryCommittedIntersectionTriangleKHR': (1, ()), 'RayQueryCommittedIntersectionGeneratedKHR': (2, ())},
936 'RayQueryIntersection': {'RayQueryCandidateIntersectionKHR': (0, ()), 'RayQueryCommittedIntersectionKHR': (1, ())},
937 'SamplerAddressingMode': {'None': (0, ()), 'ClampToEdge': (1, ()), 'Clamp': (2, ()), 'Repeat': (3, ()), 'RepeatMirrored': (4, ())},
938 'SamplerFilterMode': {'Nearest': (0, ()), 'Linear': (1, ())},
939 'Scope': {'CrossDevice': (0, ()), 'Device': (1, ()), 'Workgroup': (2, ()), 'Subgroup': (3, ()), 'Invocation': (4, ()), 'QueueFamily': (5, ()), 'QueueFamilyKHR': (5, ()), 'ShaderCallKHR': (6, ())},
940 'SourceLanguage': {'Unknown': (0, ()), 'ESSL': (1, ()), 'GLSL': (2, ()), 'OpenCL_C': (3, ()), 'OpenCL_CPP': (4, ()), 'HLSL': (5, ()), 'CPP_for_OpenCL': (6, ()), 'SYCL': (7, ()), 'HERO_C': (8, ()), 'NZSL': (9, ()), 'WGSL': (10, ()), 'Slang': (11, ()), 'Zig': (12, ()), 'Rust': (13, ()), 'Pred': (14, ()), 'ApilaJai': (15, ())},
941 'StorageClass': {'UniformConstant': (0, ()), 'Input': (1, ()), 'Uniform': (2, ()), 'Output': (3, ()), 'Workgroup': (4, ()), 'CrossWorkgroup': (5, ()), 'Private': (6, ()), 'Function': (7, ()), 'Generic': (8, ()), 'PushConstant': (9, ()), 'AtomicCounter': (10, ()), 'Image': (11, ()), 'StorageBuffer': (12, ()), 'TileImageEXT': (4172, ()), 'TileAttachmentQCOM': (4491, ()), 'NodePayloadAMDX': (5068, ()), 'CallableDataKHR': (5328, ()), 'CallableDataNV': (5328, ()), 'IncomingCallableDataKHR': (5329, ()), 'IncomingCallableDataNV': (5329, ()), 'RayPayloadKHR': (5338, ()), 'RayPayloadNV': (5338, ()), 'HitAttributeKHR': (5339, ()), 'HitAttributeNV': (5339, ()), 'IncomingRayPayloadKHR': (5342, ()), 'IncomingRayPayloadNV': (5342, ()), 'ShaderRecordBufferKHR': (5343, ()), 'ShaderRecordBufferNV': (5343, ()), 'PhysicalStorageBuffer': (5349, ()), 'PhysicalStorageBufferEXT': (5349, ()), 'HitObjectAttributeNV': (5385, ()), 'TaskPayloadWorkgroupEXT': (5402, ()), 'HitObjectAttributeEXT': (5411, ()), 'CodeSectionINTEL': (5605, ()), 'DeviceOnlyALTERA': (5936, ()), 'DeviceOnlyINTEL': (5936, ()), 'HostOnlyALTERA': (5937, ()), 'HostOnlyINTEL': (5937, ())},
942 'StoreCacheControl': {'UncachedINTEL': (0, ()), 'WriteThroughINTEL': (1, ()), 'WriteBackINTEL': (2, ()), 'StreamingINTEL': (3, ())},
943 'TensorClampMode': {'Undefined': (0, ()), 'Constant': (1, ()), 'ClampToEdge': (2, ()), 'Repeat': (3, ()), 'RepeatMirrored': (4, ())},
944}
945
946BIT_ENUMS = {
947 'CooperativeMatrixOperands': {'NoneKHR': (0, ()), 'MatrixASignedComponentsKHR': (1, ()), 'MatrixBSignedComponentsKHR': (2, ()), 'MatrixCSignedComponentsKHR': (4, ()), 'MatrixResultSignedComponentsKHR': (8, ()), 'SaturatingAccumulationKHR': (16, ())},
948 'CooperativeMatrixReduce': {'Row': (1, ()), 'Column': (2, ()), '2x2': (4, ())},
949 'FPFastMathMode': {'None': (0, ()), 'NotNaN': (1, ()), 'NotInf': (2, ()), 'NSZ': (4, ()), 'AllowRecip': (8, ()), 'Fast': (16, ()), 'AllowContract': (65536, ()), 'AllowContractFastINTEL': (65536, ()), 'AllowReassoc': (131072, ()), 'AllowReassocINTEL': (131072, ()), 'AllowTransform': (262144, ())},
950 'FragmentShadingRate': {'Vertical2Pixels': (1, ()), 'Vertical4Pixels': (2, ()), 'Horizontal2Pixels': (4, ()), 'Horizontal4Pixels': (8, ())},
951 'FunctionControl': {'None': (0, ()), 'Inline': (1, ()), 'DontInline': (2, ()), 'Pure': (4, ()), 'Const': (8, ()), 'OptNoneEXT': (65536, ()), 'OptNoneINTEL': (65536, ())},
952 'ImageOperands': {'None': (0, ()), 'Bias': (1, ('IdRef',)), 'Lod': (2, ('IdRef',)), 'Grad': (4, ('IdRef', 'IdRef')), 'ConstOffset': (8, ('IdRef',)), 'Offset': (16, ('IdRef',)), 'ConstOffsets': (32, ('IdRef',)), 'Sample': (64, ('IdRef',)), 'MinLod': (128, ('IdRef',)), 'MakeTexelAvailable': (256, ('IdScope',)), 'MakeTexelAvailableKHR': (256, ('IdScope',)), 'MakeTexelVisible': (512, ('IdScope',)), 'MakeTexelVisibleKHR': (512, ('IdScope',)), 'NonPrivateTexel': (1024, ()), 'NonPrivateTexelKHR': (1024, ()), 'VolatileTexel': (2048, ()), 'VolatileTexelKHR': (2048, ()), 'SignExtend': (4096, ()), 'ZeroExtend': (8192, ()), 'Nontemporal': (16384, ()), 'Offsets': (65536, ('IdRef',))},
953 'KernelProfilingInfo': {'None': (0, ()), 'CmdExecTime': (1, ())},
954 'LoopControl': {'None': (0, ()), 'Unroll': (1, ()), 'DontUnroll': (2, ()), 'DependencyInfinite': (4, ()), 'DependencyLength': (8, ('LiteralInteger',)), 'MinIterations': (16, ('LiteralInteger',)), 'MaxIterations': (32, ('LiteralInteger',)), 'IterationMultiple': (64, ('LiteralInteger',)), 'PeelCount': (128, ('LiteralInteger',)), 'PartialCount': (256, ('LiteralInteger',)), 'InitiationIntervalALTERA': (65536, ('LiteralInteger',)), 'InitiationIntervalINTEL': (65536, ('LiteralInteger',)), 'MaxConcurrencyALTERA': (131072, ('LiteralInteger',)), 'MaxConcurrencyINTEL': (131072, ('LiteralInteger',)), 'DependencyArrayALTERA': (262144, ('LiteralInteger',)), 'DependencyArrayINTEL': (262144, ('LiteralInteger',)), 'PipelineEnableALTERA': (524288, ('LiteralInteger',)), 'PipelineEnableINTEL': (524288, ('LiteralInteger',)), 'LoopCoalesceALTERA': (1048576, ('LiteralInteger',)), 'LoopCoalesceINTEL': (1048576, ('LiteralInteger',)), 'MaxInterleavingALTERA': (2097152, ('LiteralInteger',)), 'MaxInterleavingINTEL': (2097152, ('LiteralInteger',)), 'SpeculatedIterationsALTERA': (4194304, ('LiteralInteger',)), 'SpeculatedIterationsINTEL': (4194304, ('LiteralInteger',)), 'NoFusionALTERA': (8388608, ()), 'NoFusionINTEL': (8388608, ()), 'LoopCountALTERA': (16777216, ('LiteralInteger',)), 'LoopCountINTEL': (16777216, ('LiteralInteger',)), 'MaxReinvocationDelayALTERA': (33554432, ('LiteralInteger',)), 'MaxReinvocationDelayINTEL': (33554432, ('LiteralInteger',)), 'MultipleWaitQueuesQCOM': (268435456, ('LiteralInteger',))},
955 'MatrixMultiplyAccumulateOperands': {'None': (0, ()), 'MatrixASignedComponentsINTEL': (1, ()), 'MatrixBSignedComponentsINTEL': (2, ()), 'MatrixCBFloat16INTEL': (4, ()), 'MatrixResultBFloat16INTEL': (8, ()), 'MatrixAPackedInt8INTEL': (16, ()), 'MatrixBPackedInt8INTEL': (32, ()), 'MatrixAPackedInt4INTEL': (64, ()), 'MatrixBPackedInt4INTEL': (128, ()), 'MatrixATF32INTEL': (256, ()), 'MatrixBTF32INTEL': (512, ()), 'MatrixAPackedFloat16INTEL': (1024, ()), 'MatrixBPackedFloat16INTEL': (2048, ()), 'MatrixAPackedBFloat16INTEL': (4096, ()), 'MatrixBPackedBFloat16INTEL': (8192, ())},
956 'MemoryAccess': {'None': (0, ()), 'Volatile': (1, ()), 'Aligned': (2, ('LiteralInteger',)), 'Nontemporal': (4, ()), 'MakePointerAvailable': (8, ('IdScope',)), 'MakePointerAvailableKHR': (8, ('IdScope',)), 'MakePointerVisible': (16, ('IdScope',)), 'MakePointerVisibleKHR': (16, ('IdScope',)), 'NonPrivatePointer': (32, ()), 'NonPrivatePointerKHR': (32, ()), 'AliasScopeINTELMask': (65536, ('IdRef',)), 'NoAliasINTELMask': (131072, ('IdRef',))},
957 'MemorySemantics': {'Relaxed': (0, ()), 'None': (0, ()), 'Acquire': (2, ()), 'Release': (4, ()), 'AcquireRelease': (8, ()), 'SequentiallyConsistent': (16, ()), 'UniformMemory': (64, ()), 'SubgroupMemory': (128, ()), 'WorkgroupMemory': (256, ()), 'CrossWorkgroupMemory': (512, ()), 'AtomicCounterMemory': (1024, ()), 'ImageMemory': (2048, ()), 'OutputMemory': (4096, ()), 'OutputMemoryKHR': (4096, ()), 'MakeAvailable': (8192, ()), 'MakeAvailableKHR': (8192, ()), 'MakeVisible': (16384, ()), 'MakeVisibleKHR': (16384, ()), 'Volatile': (32768, ())},
958 'RawAccessChainOperands': {'None': (0, ()), 'RobustnessPerComponentNV': (1, ()), 'RobustnessPerElementNV': (2, ())},
959 'RayFlags': {'NoneKHR': (0, ()), 'OpaqueKHR': (1, ()), 'NoOpaqueKHR': (2, ()), 'TerminateOnFirstHitKHR': (4, ()), 'SkipClosestHitShaderKHR': (8, ()), 'CullBackFacingTrianglesKHR': (16, ()), 'CullFrontFacingTrianglesKHR': (32, ()), 'CullOpaqueKHR': (64, ()), 'CullNoOpaqueKHR': (128, ()), 'SkipTrianglesKHR': (256, ()), 'SkipBuiltinPrimitivesNV': (256, ()), 'SkipAABBsKHR': (512, ()), 'ForceOpacityMicromap2StateKHR': (1024, ()), 'ForceOpacityMicromap2StateEXT': (1024, ())},
960 'SelectionControl': {'None': (0, ()), 'Flatten': (1, ()), 'DontFlatten': (2, ())},
961 'TensorAddressingOperands': {'None': (0, ()), 'TensorView': (1, ('IdRef',)), 'DecodeFunc': (2, ('IdRef',)), 'DecodeVectorFunc': (4, ('IdRef',))},
962 'TensorOperands': {'NoneARM': (0, ()), 'NontemporalARM': (1, ()), 'OutOfBoundsValueARM': (2, ('IdRef',)), 'MakeElementAvailableARM': (4, ('IdRef',)), 'MakeElementVisibleARM': (8, ('IdRef',)), 'NonPrivateElementARM': (16, ())},
963}
964
965GLSL_STD_450 = {
966 'Acos': 17,
967 'Acosh': 23,
968 'Asin': 16,
969 'Asinh': 22,
970 'Atan': 18,
971 'Atan2': 25,
972 'Atanh': 24,
973 'Ceil': 9,
974 'Cos': 14,
975 'Cosh': 20,
976 'Cross': 68,
977 'Degrees': 12,
978 'Determinant': 33,
979 'Distance': 67,
980 'Exp': 27,
981 'Exp2': 29,
982 'FAbs': 4,
983 'FClamp': 43,
984 'FMax': 40,
985 'FMin': 37,
986 'FMix': 46,
987 'FSign': 6,
988 'FaceForward': 70,
989 'FindILsb': 73,
990 'FindSMsb': 74,
991 'FindUMsb': 75,
992 'Floor': 8,
993 'Fma': 50,
994 'Fract': 10,
995 'Frexp': 51,
996 'FrexpStruct': 52,
997 'IMix': 47,
998 'InterpolateAtCentroid': 76,
999 'InterpolateAtOffset': 78,
1000 'InterpolateAtSample': 77,
1001 'InverseSqrt': 32,
1002 'Ldexp': 53,
1003 'Length': 66,
1004 'Log': 28,
1005 'Log2': 30,
1006 'MatrixInverse': 34,
1007 'Modf': 35,
1008 'ModfStruct': 36,
1009 'NClamp': 81,
1010 'NMax': 80,
1011 'NMin': 79,
1012 'Normalize': 69,
1013 'PackDouble2x32': 59,
1014 'PackHalf2x16': 58,
1015 'PackSnorm2x16': 56,
1016 'PackSnorm4x8': 54,
1017 'PackUnorm2x16': 57,
1018 'PackUnorm4x8': 55,
1019 'Pow': 26,
1020 'Radians': 11,
1021 'Reflect': 71,
1022 'Refract': 72,
1023 'Round': 1,
1024 'RoundEven': 2,
1025 'SAbs': 5,
1026 'SClamp': 45,
1027 'SMax': 42,
1028 'SMin': 39,
1029 'SSign': 7,
1030 'Sin': 13,
1031 'Sinh': 19,
1032 'SmoothStep': 49,
1033 'Sqrt': 31,
1034 'Step': 48,
1035 'Tan': 15,
1036 'Tanh': 21,
1037 'Trunc': 3,
1038 'UClamp': 44,
1039 'UMax': 41,
1040 'UMin': 38,
1041 'UnpackDouble2x32': 65,
1042 'UnpackHalf2x16': 62,
1043 'UnpackSnorm2x16': 60,
1044 'UnpackSnorm4x8': 63,
1045 'UnpackUnorm2x16': 61,
1046 'UnpackUnorm4x8': 64,
1047}
diff --git a/tools/spirv_metal_set0.py b/tools/spirv_metal_set0.py
index 9282a60e6..766338259 100644
--- a/tools/spirv_metal_set0.py
+++ b/tools/spirv_metal_set0.py
@@ -156,19 +156,47 @@ def main(argv):
156 if len(argv) != 3: 156 if len(argv) != 3:
157 print(__doc__.strip().splitlines()[-2], file=sys.stderr) 157 print(__doc__.strip().splitlines()[-2], file=sys.stderr)
158 return 2 158 return 2
159 dis = os.environ.get("SPIRV_DIS", "spirv-dis") 159 dis, asm = _tools()
160 asm = os.environ.get("SPIRV_AS", "spirv-as") 160 text = _run([dis, argv[1]], capture_output=True, text=True).stdout
161 text = subprocess.run([dis, argv[1]], check=True, capture_output=True, text=True).stdout
162 env = re.search(r"; Version: (\d+)\.(\d+)", text) 161 env = re.search(r"; Version: (\d+)\.(\d+)", text)
163 target = f"spv{env.group(1)}.{env.group(2)}" if env else "vulkan1.2" 162 target = f"spv{env.group(1)}.{env.group(2)}" if env else "vulkan1.2"
164 subprocess.run([asm, "--target-env", target, "-", "-o", argv[2]], 163 _run([asm, "--target-env", target, "-", "-o", argv[2]], input=rewrite(text, counts), text=True)
165 input=rewrite(text, counts), check=True, text=True)
166 return 0 164 return 0
167 165
168 166
167def _tools():
168 return os.environ.get("SPIRV_DIS", "spirv-dis"), os.environ.get("SPIRV_AS", "spirv-as")
169
170
171def _run(cmd, **kwargs):
172 """subprocess.run(check=True). Windows does not name the program it could not start, so name it here."""
173 try:
174 return subprocess.run(cmd, check=True, **kwargs)
175 except OSError as e:
176 if e.filename is None:
177 e.filename = cmd[0]
178 raise
179
180
181def cli(argv):
182 """main() for the command line: a SPIRV-Tools program that cannot be started, or that rejects its input, is
183 one ERROR line and exit 1 instead of a traceback. main() itself still raises, for callers that catch it."""
184 try:
185 return main(argv)
186 except subprocess.CalledProcessError as e:
187 program = e.cmd[0] if isinstance(e.cmd, (list, tuple)) else e.cmd
188 said = next((line.strip() for line in (e.stderr or "").splitlines() if line.strip()), "")
189 print(f"ERROR: {program} failed with exit status {e.returncode}" + (f": {said}" if said else ""),
190 file=sys.stderr)
191 except OSError as e:
192 hint = " (SPIRV-Tools must be on PATH, or set SPIRV_DIS / SPIRV_AS)" if e.filename in _tools() else ""
193 print(f"ERROR: {e.filename or 'spirv_metal_set0.py'}: {e.strerror or e}{hint}", file=sys.stderr)
194 return 1
195
196
169if __name__ == "__main__": 197if __name__ == "__main__":
170 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode 198 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
171 sys.stdout.reconfigure(errors="replace") 199 sys.stdout.reconfigure(errors="replace")
172 except (AttributeError, ValueError, OSError): 200 except (AttributeError, ValueError, OSError):
173 pass 201 pass
174 sys.exit(main(sys.argv)) 202 sys.exit(cli(sys.argv))
diff --git a/tools/tex_export.py b/tools/tex_export.py
index 59d7d4c28..c3d2d9e98 100644
--- a/tools/tex_export.py
+++ b/tools/tex_export.py
@@ -92,12 +92,14 @@ def dds_bytes(w, h, fmt, payload):
92def score_image(w, h, fmt, payload, bpe): 92def score_image(w, h, fmt, payload, bpe):
93 a = None 93 a = None
94 if fmt in PILLOW_OK: 94 if fmt in PILLOW_OK:
95 from PIL import Image
96 try: 95 try:
96 from PIL import Image
97
97 im = Image.open(io.BytesIO(dds_bytes(w, h, DECODE_AS.get(fmt, fmt), payload))).convert("RGB") 98 im = Image.open(io.BytesIO(dds_bytes(w, h, DECODE_AS.get(fmt, fmt), payload))).convert("RGB")
98 a = np.asarray(im.reduce(4) if min(w, h) >= 64 else im, np.float32) 99 a = np.asarray(im.reduce(4) if min(w, h) >= 64 else im, np.float32)
99 except NotImplementedError: 100 except (ImportError, NotImplementedError, OSError):
100 pass # Pillow 13.0.0 can't decode DXGI 81 and 87 (91 as 87): score raw elements, not a tied 9e9 in export_one 101 # Some Pillow installations cannot decode these formats. Score the raw elements below.
102 a = None
101 if a is None: 103 if a is None:
102 block = FMT[fmt][1] 104 block = FMT[fmt][1]
103 we, he = (w + block - 1) // block, (h + block - 1) // block 105 we, he = (w + block - 1) // block, (h + block - 1) // block
diff --git a/tools/texoff_probe.py b/tools/texoff_probe.py
new file mode 100644
index 000000000..ae9350b47
--- /dev/null
+++ b/tools/texoff_probe.py
@@ -0,0 +1,164 @@
1r"""SHADER-337: measure the y and z texel-offset fields of image_sample_lz_o on an AMD GPU (tools/hw_oracle).
2
3 python -I tools/texoff_probe.py # the rule's expectation only (no GPU)
4 python -I tools/texoff_probe.py --oracle hw # native AMD GPU, wave32 and wave64, compared with the rule
5
6docs/design.md ("Texel offsets") has x measured on hardware (signed 6-bit field at bits [5:0], bits 6-7 ignored) and the
7y and z signs only from a structural test. Here a raw kernel samples a linear R32_SFLOAT texture whose texel holds its
8own index, with a point sampler that clamps to the last texel, so each result names the texel that was read:
9
10 2D 64x64, texel (x, y) = 64 y + x: y field = offset dword bits [13:8]
11 3D 64x1x64, texel (x, 0, z) = 64 z + x: z field = offset dword bits [21:16]
12
13Each row starts at a texel and uses one offset dword. The values are chosen so that a signed and an unsigned reading
14land on different texels (or one clamps), and some rows set the bits just above a field to see whether they are
15ignored. The rule checked is the translator's: every field is sign-extended from 6 bits, the bits above it ignored
16(tests/test_texel_offsets.py). Standard library only; the texture is built here, no game files.
17
18Exit codes: 0 every row matches the rule, 1 a mismatch, 2 harness error, 77 no hardware oracle.
19"""
20import argparse
21import os
22import struct
23import sys
24
25HERE = os.path.dirname(os.path.abspath(__file__))
26sys.path.insert(0, os.path.join(HERE, "hw_oracle"))
27
28W = 64
29H2D = 64
30D3D = 64
31SQ_RSRC_IMG_3D = 10
32CLAMP_LAST_TEXEL = 2
33
34
35def sext6(v):
36 v &= 0x3F
37 return v - 64 if v & 0x20 else v
38
39
40def clamp(v, n):
41 return max(0, min(n - 1, v))
42
43
44# (name, dim, start (x, y_or_z), offset dword)
45ROWS = [
46 # y field, 2D: from row 40 (0x20 signed is -32 -> 8, unsigned 32 -> clamps to 63; 0x3c is -4 -> 36 vs 60)
47 ("y_0x20_from40", "2d", (5, 40), 0x20 << 8),
48 ("y_0x3c_from40", "2d", (5, 40), 0x3C << 8),
49 ("y_0x1f_from10", "2d", (5, 10), 0x1F << 8), # +31 -> 41 either way (control)
50 ("y_0x20_from10", "2d", (5, 10), 0x20 << 8), # signed -32 clamps to 0, unsigned 32 -> 42
51 ("y_0x21_from40", "2d", (5, 40), 0x21 << 8), # -31 -> 9 vs 33 -> clamp 63
52 ("y_bits14_15", "2d", (5, 40), 0xC0 << 8), # field 0 with bits 14-15 set: 40 if they are ignored
53 ("y_0x3f_bit14", "2d", (5, 40), 0x7F << 8), # field 0x3f (-1) with bit 14: 39 if ignored
54 ("y_with_x", "2d", (20, 40), (0x3C << 8) | 0x3E), # x -2, y -4 together
55 # z field, 3D: same values on bits [21:16]
56 ("z_0x20_from40", "3d", (5, 40), 0x20 << 16),
57 ("z_0x3c_from40", "3d", (5, 40), 0x3C << 16),
58 ("z_0x1f_from10", "3d", (5, 10), 0x1F << 16),
59 ("z_0x20_from10", "3d", (5, 10), 0x20 << 16),
60 ("z_0x21_from40", "3d", (5, 40), 0x21 << 16),
61 ("z_bits22_23", "3d", (5, 40), 0xC0 << 16),
62 ("z_with_x_y", "3d", (20, 40), (0x3C << 16) | (0x3F << 8) | 0x3E), # y -1 on a 1-texel-high image clamps
63]
64
65
66def expected(dim, start, off):
67 x0, b0 = start
68 x = clamp(x0 + sext6(off), W)
69 if dim == "2d":
70 y = clamp(b0 + sext6(off >> 8), H2D)
71 return float(y * W + x)
72 z = clamp(b0 + sext6(off >> 16), D3D)
73 return float(z * W + x) # y is clamped to the single row
74
75
76def texture(dim):
77 n = W * (H2D if dim == "2d" else D3D)
78 return b"".join(struct.pack("<f", float(i)) for i in range(n))
79
80
81def words(arch, dim):
82 import tsharp
83 if dim == "2d":
84 return tsharp.image_words(arch, "R32_SFLOAT", W, H2D, 4)
85 t = tsharp.image_words(arch, "R32_SFLOAT", W, 1, 4)
86 t[3] = (t[3] & ~(0xF << 28)) | (SQ_RSRC_IMG_3D << 28)
87 t[4] = D3D - 1 # 3D: DEPTH = depth - 1; a 256-byte row needs no custom pitch
88 return t
89
90
91def sampler_words():
92 return [CLAMP_LAST_TEXEL | (CLAMP_LAST_TEXEL << 3) | (CLAMP_LAST_TEXEL << 6), 0, 0, 0] # point, no mips
93
94
95def kernel(arch, dim, rows):
96 import tsharp
97 t, s = words(arch, dim), sampler_words()
98 uid = dim
99 out = ["s_getpc_b64 s[4:5]", f".Lpc{uid}:", f"s_add_u32 s4, s4, .Ltex{uid}-.Lpc{uid}", "s_addc_u32 s5, s5, 0",
100 "s_and_b32 s6, s4, 255", "s_lshr_b64 s[4:5], s[4:5], 8", "s_mov_b32 s8, s4", "s_and_b32 s9, s5, 255",
101 f"s_or_b32 s9, s9, 0x{t[1]:08x}"]
102 out += [f"s_mov_b32 s{8 + i}, 0x{t[i]:08x}" for i in range(2, 8)]
103 out += [f"s_mov_b32 s{16 + i}, 0x{s[i]:08x}" for i in range(4)]
104 depth = H2D if dim == "2d" else D3D
105 for i, (_name, _d, (x0, b0), off) in enumerate(rows):
106 u, v = (x0 + 0.5) / W, (b0 + 0.5) / depth
107 out += [f"v_mov_b32 v1, 0x{off:08x}", f"v_mov_b32 v2, 0x{struct.unpack('<I', struct.pack('<f', u))[0]:08x}"]
108 if dim == "2d":
109 out += [f"v_mov_b32 v3, 0x{struct.unpack('<I', struct.pack('<f', v))[0]:08x}",
110 "image_sample_lz_o v8, v[1:3], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_2D"]
111 else:
112 out += ["v_mov_b32 v3, 0x3f000000", # t = 0.5 (the one row)
113 f"v_mov_b32 v4, 0x{struct.unpack('<I', struct.pack('<f', v))[0]:08x}",
114 "image_sample_lz_o v8, v[1:4], s[8:15], s[16:19] dmask:0x1 dim:SQ_RSRC_IMG_3D"]
115 out += ["s_waitcnt vmcnt(0)", "s_cmp_lg_u32 s6, 0", f"s_cbranch_scc0 .Lok{uid}{i}",
116 f"v_mov_b32 v8, 0x{tsharp.POISON:08x}", f".Lok{uid}{i}:",
117 f"v_mov_b32 v5, {4 * i}", "global_store_b32 v5, v8, s[2:3]"]
118 out += ["s_waitcnt vmcnt(0)", "s_endpgm", ".p2align 8", f".Ltex{uid}:"]
119 return out + tsharp._longs(texture(dim))
120
121
122def main():
123 ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
124 ap.add_argument("--oracle", choices=("rule", "hw"), default="rule")
125 a = ap.parse_args()
126 if a.oracle == "rule":
127 for name, dim, start, off in ROWS:
128 print(f"{name:16} offset 0x{off:06x} rule {expected(dim, start, off):.0f}")
129 return 0
130 import asm
131 import runner
132 try:
133 oracle = runner.Oracle()
134 except runner.Unavailable as e:
135 print(f"hardware oracle unavailable: {e}")
136 return 77
137 print(f"device: {oracle.device}")
138 bad = 0
139 for dim in ("2d", "3d"):
140 rows = [r for r in ROWS if r[1] == dim]
141 got = {}
142 for wave in (32, 64):
143 res = oracle.run([asm.Kernel(kernel(oracle.arch, dim, rows), wave=wave, threads=1, words=len(rows),
144 raw=True, vgprs=16, sgprs=24)])[0]
145 if isinstance(res, str):
146 print(f"{dim} wave{wave}: kernel rejected: {res}")
147 return 2
148 got[wave] = [struct.unpack("<f", struct.pack("<I", w))[0] for w in res]
149 for i, (name, _d, start, off) in enumerate(rows):
150 want = expected(dim, start, off)
151 g32, g64 = got[32][i], got[64][i]
152 ok = g32 == want and g64 == want
153 bad += not ok
154 extra = "" if g32 == g64 else f" (wave64 {g64:.0f})"
155 print(f"{name:16} offset 0x{off:06x} hw {g32:6.0f}{extra:14} rule {want:6.0f} {'ok' if ok else 'DIFFERS'}")
156 return 1 if bad else 0
157
158
159if __name__ == "__main__":
160 try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
161 sys.stdout.reconfigure(errors="replace")
162 except (AttributeError, ValueError, OSError):
163 pass
164 sys.exit(main())
diff --git a/tools/text_tables.py b/tools/text_tables.py
index 63d4a4e31..56031a25b 100644
--- a/tools/text_tables.py
+++ b/tools/text_tables.py
@@ -111,7 +111,7 @@ def string_tables(buf: bytes):
111 continue 111 continue
112 start = blob + (struct.unpack_from("<Q", buf, at)[0] >> 20) 112 start = blob + (struct.unpack_from("<Q", buf, at)[0] >> 20)
113 end = buf.find(b"\0", start, blob + blob_bytes) 113 end = buf.find(b"\0", start, blob + blob_bytes)
114 if blob <= start and end > start: 114 if blob <= start <= end:
115 out[h] = buf[start:end].decode("utf-8", "replace") 115 out[h] = buf[start:end].decode("utf-8", "replace")
116 if out: 116 if out:
117 yield out 117 yield out
@@ -170,11 +170,14 @@ def _is_resource(data: bytes) -> bool:
170 170
171 171
172def _chains(rows, read): 172def _chains(rows, read):
173 """(offset, bytes) per logical blob: a stream plus the streams that continue a full 64 KiB one.""" 173 """(offset, bytes) per logical blob: a stream plus the streams that continue a full one.
174
175 A stream is full when its size is a whole number of 64 KiB blocks: a resource's first stream is often 128 or
176 192 KiB (docs/page_directory.md), not only 64 KiB, and its descriptors then end in the stream that follows."""
174 cur_off, parts, last = None, [], 0 177 cur_off, parts, last = None, [], 0
175 for row in rows: 178 for row in rows:
176 data = read(row) 179 data = read(row)
177 continues = (cur_off is not None and last == BLOCK and not _is_resource(data) 180 continues = (cur_off is not None and last > 0 and last % BLOCK == 0 and not _is_resource(data)
178 and data[:4] != b"PSIN" and data[:4] != b"RBF0") 181 and data[:4] != b"PSIN" and data[:4] != b"RBF0")
179 if continues and sum(map(len, parts)) + len(data) <= MAX_RESOURCE_BYTES: 182 if continues and sum(map(len, parts)) + len(data) <= MAX_RESOURCE_BYTES:
180 parts.append(data) 183 parts.append(data)
diff --git a/tools/tile_probe.py b/tools/tile_probe.py
index 1492a792f..04b47bd12 100644
--- a/tools/tile_probe.py
+++ b/tools/tile_probe.py
@@ -13,6 +13,10 @@ import sys
13 13
14import numpy as np 14import numpy as np
15 15
16# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module.
17sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
18from report_paths import same_report_path # noqa: E402
19
16 20
17def morton_decode(i, bits): 21def morton_decode(i, bits):
18 """Split a Z-order index into (x, y), x taking the even bits.""" 22 """Split a Z-order index into (x, y), x taking the even bits."""
@@ -137,15 +141,6 @@ def render(data, offset, bpe, wpx, mode, out):
137 return im.size 141 return im.size
138 142
139 143
140def same_report_path(first, second):
141 if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)):
142 return True
143 try:
144 return os.path.samefile(first, second)
145 except OSError:
146 return False
147
148
149def check_preview_path(out, blob): 144def check_preview_path(out, blob):
150 """Refuse a preview that would destroy the sample, and create its folder. 145 """Refuse a preview that would destroy the sample, and create its folder.
151 146
diff --git a/tools/user_sgpr_census.py b/tools/user_sgpr_census.py
index bdb49ff12..e64075e72 100644
--- a/tools/user_sgpr_census.py
+++ b/tools/user_sgpr_census.py
@@ -21,6 +21,9 @@ Usage:
21 python -I tools/user_sgpr_census.py <spirv/index.json> [--json OUT] 21 python -I tools/user_sgpr_census.py <spirv/index.json> [--json OUT]
22 python -I tools/user_sgpr_census.py <spirv/index.json> --expect ps=8 vs=8 cs=4 ms=16 22 python -I tools/user_sgpr_census.py <spirv/index.json> --expect ps=8 vs=8 cs=4 ms=16
23 (exit 1 if, for a listed stage, the most common lowest-pointer SGPR is not the expected one) 23 (exit 1 if, for a listed stage, the most common lowest-pointer SGPR is not the expected one)
24
25An index that cannot be read, is not JSON or is not the shape tools/shader_meta.py writes, and a --json path that
26cannot be written, each give one ERROR line and exit 2.
24""" 27"""
25import argparse 28import argparse
26import json 29import json
@@ -84,6 +87,36 @@ def census(index, base=None):
84 return out 87 return out
85 88
86 89
90def load_index(path):
91 """The index as {name: entry}. ValueError with a one-line reason when the file cannot be read, is not JSON or
92 is not the shape census() reads; the wording follows tools/root_sig_contract.py, which reads the same file."""
93 try:
94 with open(path, encoding="utf-8") as f:
95 index = json.load(f)
96 except (OSError, ValueError, RecursionError) as e: # ValueError: not JSON, or not UTF-8
97 reason = getattr(e, "strerror", None) or e
98 raise ValueError(f"cannot read {path}: {reason}") from None
99 if not isinstance(index, dict):
100 raise ValueError(f"{path}: expected a JSON object of shader -> metadata entries")
101 for name, entry in index.items():
102 if not isinstance(entry, dict):
103 raise ValueError(f"{path}: {name}: each shader entry must be a JSON object")
104 if not isinstance(entry.get("stage", ""), str):
105 raise ValueError(f"{path}: {name}: 'stage' must be a string")
106 reads = entry.get("user_sgpr_reads") or []
107 if not isinstance(reads, list):
108 raise ValueError(f"{path}: {name}: 'user_sgpr_reads' must be a JSON array")
109 for read in reads:
110 if not isinstance(read, dict) or "sgpr" not in read or "kind" not in read:
111 raise ValueError(f"{path}: {name}: each read needs 'sgpr' and 'kind' fields")
112 sgpr = read["sgpr"]
113 if isinstance(sgpr, bool) or not isinstance(sgpr, int) or sgpr < 0:
114 raise ValueError(f"{path}: {name}: each read 'sgpr' must be a nonnegative integer")
115 if not isinstance(read["kind"], str):
116 raise ValueError(f"{path}: {name}: each read kind must be a string")
117 return index
118
119
87def stage_sgpr(text): 120def stage_sgpr(text):
88 stage, _, value = text.partition("=") 121 stage, _, value = text.partition("=")
89 message = f"expected STAGE=SGPR with a nonnegative SGPR: {text!r}" 122 message = f"expected STAGE=SGPR with a nonnegative SGPR: {text!r}"
@@ -109,10 +142,13 @@ def main(argv=None):
109 try: 142 try:
110 if os.path.samefile(a.index, a.json): 143 if os.path.samefile(a.index, a.json):
111 ap.error("--json must not overwrite the input index") 144 ap.error("--json must not overwrite the input index")
112 except FileNotFoundError: 145 except OSError:
113 pass 146 pass # a missing or unreachable --json path is not the index; writing it reports the error
114 with open(a.index, encoding="utf-8") as f: 147 try:
115 index = json.load(f) 148 index = load_index(a.index)
149 except ValueError as e:
150 print(f"ERROR: {e}", file=sys.stderr)
151 return 2
116 summary = census(index, dict(a.base)) 152 summary = census(index, dict(a.base))
117 for stage, s in summary.items(): 153 for stage, s in summary.items():
118 top = s["most_common_lowest_pointer_sgpr"] 154 top = s["most_common_lowest_pointer_sgpr"]
@@ -121,8 +157,12 @@ def main(argv=None):
121 f"pointer gaps {s['pointer_gap']}; after a ptr32 {s['after_ptr32']}" 157 f"pointer gaps {s['pointer_gap']}; after a ptr32 {s['after_ptr32']}"
122 + (f"; below base {s['below_base']}" if "below_base" in s else "")) 158 + (f"; below base {s['below_base']}" if "below_base" in s else ""))
123 if a.json: 159 if a.json:
124 with open(a.json, "w", encoding="utf-8", newline="\n") as f: 160 try:
125 json.dump(summary, f, indent=1, sort_keys=True) 161 with open(a.json, "w", encoding="utf-8", newline="\n") as f:
162 json.dump(summary, f, indent=1, sort_keys=True)
163 except OSError as e:
164 print(f"ERROR: cannot write {a.json}: {e.strerror or e}", file=sys.stderr)
165 return 2
126 bad = [] 166 bad = []
127 for stage, sgpr in a.expect: 167 for stage, sgpr in a.expect:
128 got = summary.get(stage, {}).get("most_common_lowest_pointer_sgpr") 168 got = summary.get(stage, {}).get("most_common_lowest_pointer_sgpr")
diff --git a/tools/valu_fuzz.py b/tools/valu_fuzz.py
index ed6c24e0d..ca3de6d8a 100644
--- a/tools/valu_fuzz.py
+++ b/tools/valu_fuzz.py
@@ -303,9 +303,8 @@ def f16_op(name, a, b, c=None):
303 pick = (va >= vb) if name == "max" else (va <= vb) 303 pick = (va >= vb) if name == "max" else (va <= vb)
304 return (a if pick else b) & M16, False 304 return (a if pick else b) & M16, False
305 if name == "med3": 305 if name == "med3":
306 vals = sorted([(va, a), (vb, b), (vc, c)], key=lambda x: x[0]) 306 # Half decoding loses the sign of zero. The documented med3 ordering puts -0 before +0.
307 if len({v for v, _ in vals}) < 3 and len({h & M16 for _, h in vals}) == 3: 307 vals = sorted(((va, a), (vb, b), (vc, c)), key=lambda item: (item[0], -f16_sign(item[1])))
308 return 0, True
309 return vals[1][1] & M16, False 308 return vals[1][1] & M16, False
310 raise ValueError(name) 309 raise ValueError(name)
311 310
diff --git a/tools/wave64_halves.py b/tools/wave64_halves.py
index 1de05ef83..dc8b2466d 100644
--- a/tools/wave64_halves.py
+++ b/tools/wave64_halves.py
@@ -197,6 +197,8 @@ class Analysis:
197 def __init__(self, blocks, succ, masks, stage): 197 def __init__(self, blocks, succ, masks, stage):
198 self.blocks, self.succ, self.masks, self.stage = blocks, succ, masks or {}, stage 198 self.blocks, self.succ, self.masks, self.stage = blocks, succ, masks or {}, stage
199 self.n = len(blocks) 199 self.n = len(blocks)
200 self.vgprs = sorted({r[1] for b in blocks for ins in b for x in ins["args"]
201 for r in _regs(x) if isinstance(r, tuple) and r[0] == "v"})
200 self.tok = {("e",): (None, None, True)} # exec token -> (parent token, exec tag after, exec is the entry exec) 202 self.tok = {("e",): (None, None, True)} # exec token -> (parent token, exec tag after, exec is the entry exec)
201 self.stale = set() 203 self.stale = set()
202 self.voted = {} # block -> mask register key the terminating branch votes on 204 self.voted = {} # block -> mask register key the terminating branch votes on
@@ -218,6 +220,43 @@ class Analysis:
218 t |= CTRL 220 t |= CTRL
219 return t 221 return t
220 222
223 LMOD_KEEP = ("v_mov_b32", "v_add_nc_u32", "v_add_u32", "v_sub_nc_u32", "v_subrev_nc_u32", "v_sub_u32",
224 "v_subrev_u32", "v_xor_b32", "v_or_b32", "v_and_b32")
225
226 def lmod(self, st, ins, a):
227 """k when the operand is the same in the wave and in a half modulo 2**k: 32 for a partition-invariant value
228 (an immediate, an untainted register), the tag's k for a lane id, -1 for anything else."""
229 if a.get("k") in ("imm", "fimm"):
230 return 32
231 if self.is_mask(ins, a) or a.get("neg") or a.get("abs"):
232 return -1
233 regs = _regs(a)
234 if not regs or self.rd(st, ins, a):
235 if regs and self.rd(st, ins, a) == LANE and all(st["g"].get(r, ("",))[0] == "lmod" for r in regs):
236 return min(st["g"][r][1] for r in regs)
237 return -1
238 return 32
239
240 def lmod_result(self, st, ins, op, a):
241 """k of a VALU result whose only partition-dependent source is a lane id exact modulo 2**k: sums,
242 differences and bitwise ops with invariant values keep k, a left shift by an immediate c raises it to k + c."""
243 # SDWA selects, DPP, op_sel and integer clamp change the value: no tag
244 mods = ins.get("mods") or []
245 if ins["op"].endswith(("_sdwa", "_dpp")) or any(
246 m == "clamp" or m.startswith(("op_sel", "dst_unused")) or "_sel:" in m for m in mods):
247 return None
248 src = a[1:]
249 ks = [self.lmod(st, ins, x) for x in src]
250 if not src or min(ks) < 0:
251 return None
252 if op in self.LMOD_KEEP:
253 return min(ks)
254 if op == "v_lshlrev_b32" and len(src) == 2 and src[0].get("k") == "imm":
255 return min(32, ks[1] + (src[0]["v"] & 31))
256 if op in ("v_lshl_add_u32", "v_lshl_or_b32") and len(src) == 3 and src[1].get("k") == "imm":
257 return min(32, ks[0] + (src[1]["v"] & 31), ks[2])
258 return None
259
221 def join(self, a, b, blk=0): 260 def join(self, a, b, blk=0):
222 t = dict(a["t"]) 261 t = dict(a["t"])
223 for k, v in b["t"].items(): 262 for k, v in b["t"].items():
@@ -271,11 +310,33 @@ class Analysis:
271 st[key].pop(r, None) 310 st[key].pop(r, None)
272 return 311 return
273 self.new_rank = self.new_base = None 312 self.new_rank = self.new_base = None
313 op, a = base_op(ins["op"]), ins["args"]
274 dests, srcs, _, uses = operands(ins) 314 dests, srcs, _, uses = operands(ins)
275 read = [r for x in srcs for r in _regs(x)] + [r for r in uses if r != "exec"] 315 read = [r for x in srcs for r in _regs(x)] + [r for r in uses if r != "exec"]
316 if op == "v_movrels_b32" and len(a) > 1:
317 src_base = a[1]["r"] if a[1].get("k") == "vgpr" else 0
318 read.extend(("v", vr) for vr in self.vgprs if vr >= src_base)
319 dyn_v = op in ("v_movreld_b32", "v_movrelsd_b32", "v_movrelsd_2_b32", "v_swaprel_b32") and len(a) >= 2
320 if dyn_v:
321 dst_base = (min(a[0]["r"], a[1]["r"])
322 if op == "v_swaprel_b32" and a[0].get("k") == "vgpr" and a[1].get("k") == "vgpr"
323 else (a[0]["r"] if a[0].get("k") == "vgpr" else 0))
324 if op != "v_movreld_b32":
325 src_base = dst_base if op == "v_swaprel_b32" else (a[1]["r"] if a[1].get("k") == "vgpr" else 0)
326 read.extend(("v", vr) for vr in self.vgprs if vr >= src_base)
276 rk = frozenset().union(*[st["r"].get(r, frozenset()) for r in read]) 327 rk = frozenset().union(*[st["r"].get(r, frozenset()) for r in read])
277 bs = frozenset().union(*[st["b"].get(r, frozenset()) for r in read]) 328 bs = frozenset().union(*[st["b"].get(r, frozenset()) for r in read])
278 self.transfer(n, i, ins, st, ev) 329 self.transfer(n, i, ins, st, ev)
330 if dyn_v:
331 for vr in sorted(set(self.vgprs) | {dst_base}):
332 if vr < dst_base:
333 continue
334 r = ("v", vr)
335 t = st["t"].get(r, 0)
336 for key, bit, inherited in (("r", RNK, rk), ("b", BASE, bs)):
337 if t & bit and inherited:
338 st[key][r] = st[key].get(r, frozenset()) | inherited
339 return
279 for d in dests: 340 for d in dests:
280 for r in _regs(d): 341 for r in _regs(d):
281 if r == "exec": 342 if r == "exec":
@@ -357,6 +418,10 @@ class Analysis:
357 addr, data = [], list(srcs) 418 addr, data = [], list(srcs)
358 if op != "exp" and srcs: 419 if op != "exp" and srcs:
359 data, addr = [srcs[0]], list(srcs[1:]) 420 data, addr = [srcs[0]], list(srcs[1:])
421 if self.stage == "gs" and op.startswith(("ds_write", "ds_store")):
422 # ds_write vaddr, vdata...: in a legacy GS the write is an output slot from its offset alone
423 # (rdna2spirv.gs_ds drops the VGPR address, the lane's GSVS area), so only the data is observable
424 data, addr = list(srcs[1:]), []
360 dt = 0 425 dt = 0
361 for x in data: 426 for x in data:
362 dt |= self.rd(st, ins, x) | (MASKD | X if self.is_mask(ins, x) and x.get("k") != "imm" else 0) 427 dt |= self.rd(st, ins, x) | (MASKD | X if self.is_mask(ins, x) and x.get("k") != "imm" else 0)
@@ -447,7 +512,17 @@ class Analysis:
447 m, acc = a[1], a[2] 512 m, acc = a[1], a[2]
448 tacc = self.rd(st, ins, acc) 513 tacc = self.rd(st, ins, acc)
449 if m.get("k") == "imm" and m["v"] in (-1, 0xFFFFFFFF): 514 if m.get("k") == "imm" and m["v"] in (-1, 0xFFFFFFFF):
450 put(a[0], LANE | tacc) 515 # v_mbcnt_lo(-1, 0) then v_mbcnt_hi(-1, that) is the lane id: 0..63 in the wave, 0..31 in a half,
516 # so the two differ by a multiple of 32 (tag ("lmod", 5)); the low count alone does not (lanes 32..63
517 # count 32 in the wave)
518 if op == "v_mbcnt_lo_u32_b32" and acc.get("k") == "imm" and acc["v"] == 0:
519 tag = ("lane_lo",)
520 elif op == "v_mbcnt_hi_u32_b32" and tacc == LANE and _regs(acc) and \
521 st["g"].get(_regs(acc)[0]) == ("lane_lo",):
522 tag = ("lmod", 5)
523 else:
524 tag = None
525 put(a[0], LANE | tacc, tag)
451 elif self.is_mask(ins, m): 526 elif self.is_mask(ins, m):
452 if m.get("k") == "special" and m.get("t", "").startswith("exec"): 527 if m.get("k") == "special" and m.get("t", "").startswith("exec"):
453 token = st["x"] 528 token = st["x"]
@@ -514,6 +589,12 @@ class Analysis:
514 or any(m.startswith("row_") or m.startswith("quad_perm") for m in mods): 589 or any(m.startswith("row_") or m.startswith("quad_perm") for m in mods):
515 bad = any(m.startswith(DPP_BAD) for m in mods) 590 bad = any(m.startswith(DPP_BAD) for m in mods)
516 put_t = t_src | (X if bad else 0) 591 put_t = t_src | (X if bad else 0)
592 # a wave64 ds_bpermute/ds_permute works on each half (ISA 10.4.4) and uses address bits 2..6 only, so a
593 # lane-id address that is the same modulo 128 in the wave and in a half reads/writes the same lane
594 if op in ("ds_bpermute_b32", "ds_permute_b32") and len(a) >= 3 and self.lmod(st, ins, a[1]) >= 7:
595 put_t = self.rd(st, ins, a[2])
596 for r in uses:
597 put_t |= T.get(r, 0) | (CTRL if (id(ins), r) in self.stale else 0)
517 for d in dests: 598 for d in dests:
518 put(d, put_t) 599 put(d, put_t)
519 return 600 return
@@ -641,6 +722,9 @@ class Analysis:
641 T[k] = T.get(k, 0) | X 722 T[k] = T.get(k, 0) | X
642 if wt: 723 if wt:
643 bits_violation(wt) 724 bits_violation(wt)
725 for vr in self.vgprs:
726 if vr >= dst_base:
727 T[("v", vr)] = T.get(("v", vr), 0) | wt
644 T[("v", dst_base)] = T.get(("v", dst_base), 0) | wt 728 T[("v", dst_base)] = T.get(("v", dst_base), 0) | wt
645 return 729 return
646 730
@@ -668,6 +752,10 @@ class Analysis:
668 if op in ("v_mov_b32", "v_mov_b32_e32") and len(srcs) == 1 and tj & CNT and _regs(srcs[0]): 752 if op in ("v_mov_b32", "v_mov_b32_e32") and len(srcs) == 1 and tj & CNT and _regs(srcs[0]):
669 ctok = self.cnt_token(st, _regs(srcs[0])[0]) 753 ctok = self.cnt_token(st, _regs(srcs[0])[0])
670 tag = ("cnt", ctok) if ctok is not None else None 754 tag = ("cnt", ctok) if ctok is not None else None
755 if tag is None and tj == LANE and len(dests) == 1:
756 k = self.lmod_result(st, ins, op, a)
757 if k is not None:
758 tag = ("lmod", k)
671 if st["xg"] and st["xg"][0] == "elect" and dests: 759 if st["xg"] and st["xg"][0] == "elect" and dests:
672 tj |= ELECT 760 tj |= ELECT
673 tag = ("elect", st["xg"][1], ctok) 761 tag = ("elect", st["xg"][1], ctok)
@@ -896,8 +984,7 @@ class Analysis:
896 if op in ("s_waitcnt", "s_nop"): 984 if op in ("s_waitcnt", "s_nop"):
897 continue 985 continue
898 a = ins["args"] 986 a = ins["args"]
899 if op.startswith(("s_and_saveexec_b64", "s_andn2_saveexec_b64", 987 if op.startswith(("s_and_saveexec_b64", "s_and_wrexec_b64")) and len(a) == 2:
900 "s_and_wrexec_b64", "s_andn2_wrexec_b64")) and len(a) == 2:
901 return (_regs(a[1]) or [None])[0] == reg 988 return (_regs(a[1]) or [None])[0] == reg
902 if op in ("s_and_b64",) and len(a) == 3 and _regs(a[0]) == ["exec"]: 989 if op in ("s_and_b64",) and len(a) == 3 and _regs(a[0]) == ["exec"]:
903 return reg in [(_regs(x) or [None])[0] for x in a[1:] if _regs(x) != ["exec"]] 990 return reg in [(_regs(x) or [None])[0] for x in a[1:] if _regs(x) != ["exec"]]
diff --git a/tools/world_build.py b/tools/world_build.py
index 28f2fe76d..10916e36a 100644
--- a/tools/world_build.py
+++ b/tools/world_build.py
@@ -439,13 +439,13 @@ def _pack_model_job(job: tuple) -> tuple[int, dict | None]:
439 } 439 }
440 440
441 441
442_PNG_CACHE: dict[str, bytes | None] = {} 442_PNG_CACHE: dict[tuple[str, int], bytes | None] = {}
443_PNG_CACHE_BUDGET = 256 * 1024 * 1024 443_PNG_CACHE_BUDGET = 256 * 1024 * 1024
444 444
445 445
446def _png_for(dds_path: str, max_tex_size: int) -> bytes | None: 446def _png_for(dds_path: str, max_tex_size: int) -> bytes | None:
447 """Decode a DDS to PNG once per worker, keeping at most about 256 MB of PNGs (oldest dropped first).""" 447 """Decode a DDS to PNG once per worker, keeping at most about 256 MB of PNGs (oldest dropped first)."""
448 key = os.path.normcase(os.path.abspath(dds_path)) 448 key = (os.path.normcase(os.path.abspath(dds_path)), max_tex_size)
449 if key in _PNG_CACHE: 449 if key in _PNG_CACHE:
450 return _PNG_CACHE[key] 450 return _PNG_CACHE[key]
451 dds_mod = _get_dds_png() 451 dds_mod = _get_dds_png()
@@ -1184,7 +1184,7 @@ def _write_json_atomic(path: str, data: dict, replace=None) -> None:
1184 tmp_path = None 1184 tmp_path = None
1185 try: 1185 try:
1186 with tempfile.NamedTemporaryFile( 1186 with tempfile.NamedTemporaryFile(
1187 mode="w", encoding="utf-8", dir=parent, prefix=".world-", suffix=".tmp", delete=False, 1187 mode="w", encoding="utf-8", newline="\n", dir=parent, prefix=".world-", suffix=".tmp", delete=False,
1188 ) as f: 1188 ) as f:
1189 tmp_path = f.name 1189 tmp_path = f.name
1190 json.dump(data, f, indent=2, allow_nan=False) 1190 json.dump(data, f, indent=2, allow_nan=False)
diff --git a/tools/world_lights_paths.py b/tools/world_lights_paths.py
index 75d56eadd..9b7474db2 100644
--- a/tools/world_lights_paths.py
+++ b/tools/world_lights_paths.py
@@ -41,6 +41,7 @@ import struct
41import sys 41import sys
42import tempfile 42import tempfile
43import zlib 43import zlib
44from collections.abc import Sequence
44from concurrent.futures import ProcessPoolExecutor 45from concurrent.futures import ProcessPoolExecutor
45 46
46_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) 47_TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
@@ -266,14 +267,23 @@ def quat_rotate(q, v):
266 return [v[0] + w * tx + (y * tz - z * ty), v[1] + w * ty + (z * tx - x * tz), v[2] + w * tz + (x * ty - y * tx)] 267 return [v[0] + w * tx + (y * tz - z * ty), v[1] + w * ty + (z * tx - x * tz), v[2] + w * tz + (x * ty - y * tx)]
267 268
268 269
269def place(local, direction, position, rotation, scale_xy, scale_z): 270def place(
271 local: Sequence[float],
272 direction: Sequence[float] | None,
273 position: Sequence[float],
274 rotation: Sequence[float],
275 scale_xy: float | None,
276 scale_z: float | None,
277) -> tuple[list[float], list[float] | None]:
270 """World position and direction of a model-space light under an entity's stored transform. 278 """World position and direction of a model-space light under an entity's stored transform.
271 279
272 The stored quaternion is the inverse of the entity rotation (docs/world.md), so it is conjugated here. 280 The stored quaternion is the inverse of the entity rotation (docs/world.md), so it is conjugated here.
273 """ 281 """
274 x, y, z, w = rotation 282 x, y, z, w = rotation
275 q = (-x, -y, -z, w) 283 q = (-x, -y, -z, w)
276 scaled = [local[0] * scale_xy, local[1] * scale_xy, local[2] * scale_z] 284 xy = 1.0 if scale_xy is None else scale_xy
285 z_scale = 1.0 if scale_z is None else scale_z
286 scaled = [local[0] * xy, local[1] * xy, local[2] * z_scale]
277 p = quat_rotate(q, scaled) 287 p = quat_rotate(q, scaled)
278 return [position[0] + p[0], position[1] + p[1], position[2] + p[2]], (quat_rotate(q, direction) if direction else None) 288 return [position[0] + p[0], position[1] + p[1], position[2] + p[2]], (quat_rotate(q, direction) if direction else None)
279 289
@@ -529,7 +539,7 @@ def inspect_resource(data, lights_out=False):
529 for L in lights: 539 for L in lights:
530 local = [off[k] + L.get("position120", [0, 0, 0])[k] for k in range(3)] 540 local = [off[k] + L.get("position120", [0, 0, 0])[k] for k in range(3)]
531 p, d = place(local, L.get("direction"), t["position"], t["rotation"], 541 p, d = place(local, L.get("direction"), t["position"], t["rotation"],
532 t["scaleXY"] or 1.0, t["scaleZ"] or 1.0) 542 t["scaleXY"], t["scaleZ"])
533 world.append(_light_row(p, d, L, "entity", t["archetypeName"])) 543 world.append(_light_row(p, d, L, "entity", t["archetypeName"]))
534 st["lights_entity_in_map_placed"] += len(lights) 544 st["lights_entity_in_map_placed"] += len(lights)
535 out["lights"] = st 545 out["lights"] = st
@@ -687,7 +697,7 @@ def summarize(total, entities=None, lights_out=None):
687 for L in ls: 697 for L in ls:
688 local = [L["offset"][k] + L.get("position120", [0, 0, 0])[k] for k in range(3)] 698 local = [L["offset"][k] + L.get("position120", [0, 0, 0])[k] for k in range(3)]
689 p, d = place(local, L.get("direction"), e["position"], e["rotation"], 699 p, d = place(local, L.get("direction"), e["position"], e["rotation"],
690 e.get("scale_xy") or 1.0, e.get("scale_z") or 1.0) 700 e.get("scale_xy"), e.get("scale_z"))
691 out.write(json.dumps(_light_row(p, d, L, "archetype", a), 701 out.write(json.dumps(_light_row(p, d, L, "archetype", a),
692 separators=(",", ":")) + "\n") 702 separators=(",", ":")) + "\n")
693 finally: 703 finally:
@@ -749,6 +759,9 @@ def main(argv=None):
749 if a.jobs < 1: 759 if a.jobs < 1:
750 print("ERROR: --jobs must be at least 1", file=sys.stderr) 760 print("ERROR: --jobs must be at least 1", file=sys.stderr)
751 return 2 761 return 2
762 if a.limit is not None and a.limit < 1:
763 print("ERROR: --limit must be at least 1", file=sys.stderr)
764 return 2
752 if not os.path.isfile(a.archive): 765 if not os.path.isfile(a.archive):
753 print(f"ERROR: {a.archive}: no such file", file=sys.stderr) 766 print(f"ERROR: {a.archive}: no such file", file=sys.stderr)
754 return 2 767 return 2
diff --git a/tools/world_names.py b/tools/world_names.py
index 06152aac5..ec6659458 100644
--- a/tools/world_names.py
+++ b/tools/world_names.py
@@ -36,6 +36,10 @@ import re
36import sys 36import sys
37import tempfile 37import tempfile
38 38
39# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module.
40sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
41from report_paths import same_report_path # noqa: E402
42
39MASK32 = 0xFFFFFFFF 43MASK32 = 0xFFFFFFFF
40MASK64 = 0xFFFFFFFFFFFFFFFF 44MASK64 = 0xFFFFFFFFFFFFFFFF
41 45
@@ -426,7 +430,8 @@ def load_rows(path: str) -> list[dict]:
426 430
427 431
428def resolve_maps(rows, dictionary: NameDictionary, *, include_derived: bool = False) -> dict: 432def resolve_maps(rows, dictionary: NameDictionary, *, include_derived: bool = False) -> dict:
429 names = {parse_u64(row.get("map_name", row.get("name"))) for row in rows} 433 map_rows = [row for row in rows if isinstance(row, dict) and row.get("kind") in (None, "map")]
434 names = {parse_u64(row.get("map_name", row.get("name"))) for row in map_rows}
430 names.discard(None) 435 names.discard(None)
431 stats = { 436 stats = {
432 "rows": 0, "name_present": 0, "name_resolved": 0, "name_verified": 0, 437 "rows": 0, "name_present": 0, "name_resolved": 0, "name_verified": 0,
@@ -434,11 +439,7 @@ def resolve_maps(rows, dictionary: NameDictionary, *, include_derived: bool = Fa
434 "parent_present": 0, "parent_resolved": 0, "parent_ambiguous": 0, 439 "parent_present": 0, "parent_resolved": 0, "parent_ambiguous": 0,
435 "parent_unresolved": 0, "parent_links": 0, "parent_links_resolved": 0, 440 "parent_unresolved": 0, "parent_links": 0, "parent_links_resolved": 0,
436 } 441 }
437 for row in rows: 442 for row in map_rows:
438 if not isinstance(row, dict):
439 continue
440 if row.get("kind") not in (None, "map"):
441 continue
442 stats["rows"] += 1 443 stats["rows"] += 1
443 name = parse_u64(row.get("map_name", row.get("name"))) 444 name = parse_u64(row.get("map_name", row.get("name")))
444 parent = parse_u64(row.get("parent")) 445 parent = parse_u64(row.get("parent"))
@@ -543,15 +544,6 @@ def _load_json(path: str) -> dict:
543 return json.load(handle) 544 return json.load(handle)
544 545
545 546
546def _same_report_path(first: str, second: str) -> bool:
547 if os.path.normcase(os.path.realpath(first)) == os.path.normcase(os.path.realpath(second)):
548 return True
549 try:
550 return os.path.samefile(first, second)
551 except OSError:
552 return False
553
554
555def _build(args) -> int: 547def _build(args) -> int:
556 if not (args.manifest or args.scan or args.names or args.xml or args.rpf9_names): 548 if not (args.manifest or args.scan or args.names or args.xml or args.rpf9_names):
557 print("build: at least one --manifest/--scan/--names/--rpf9-names/--xml source is required", 549 print("build: at least one --manifest/--scan/--names/--rpf9-names/--xml source is required",
@@ -571,7 +563,7 @@ def _build(args) -> int:
571def _resolve(args) -> int: 563def _resolve(args) -> int:
572 if args.out: 564 if args.out:
573 for path in (args.dict, *args.maps, *args.archetypes): 565 for path in (args.dict, *args.maps, *args.archetypes):
574 if _same_report_path(args.out, path): 566 if same_report_path(args.out, path):
575 raise ValueError( 567 raise ValueError(
576 f"resolve: --out {args.out} would overwrite input {path}") 568 f"resolve: --out {args.out} would overwrite input {path}")
577 try: 569 try:
diff --git a/tools/xdxr_bvh.py b/tools/xdxr_bvh.py
index e8fcefde3..c6a636eaa 100644
--- a/tools/xdxr_bvh.py
+++ b/tools/xdxr_bvh.py
@@ -259,7 +259,7 @@ def _write_parents(buf, parents_off, elements_off, end, parent_of, root_ptr):
259 259
260def _write_header(buf, flags, end, n_elements, bounds, nodes_off, root, elements_off, parents_off): 260def _write_header(buf, flags, end, n_elements, bounds, nodes_off, root, elements_off, parents_off):
261 lo, hi = bounds 261 lo, hi = bounds
262 struct.pack_into("<4I6fIiIIII", buf, 0, flags, end // UNIT, 0, n_elements, *lo, *hi, 262 struct.pack_into("<4I6fIiIIII", buf, 0, flags, end // UNIT - 1, 0, n_elements, *lo, *hi,
263 nodes_off, 0, root, elements_off, parents_off, 0) 263 nodes_off, 0, root, elements_off, parents_off, 0)
264 264
265 265
@@ -651,8 +651,8 @@ def validate(data, expect_bottom=None):
651 if flags & (FLAG_COMPRESSED | FLAG_DEHYDRATED): 651 if flags & (FLAG_COMPRESSED | FLAG_DEHYDRATED):
652 errs.append("compressed or dehydrated BVH: not a runtime tree (docs/bvh.md 3.1)") 652 errs.append("compressed or dehydrated BVH: not a runtime tree (docs/bvh.md 3.1)")
653 return errs 653 return errs
654 if units * UNIT != len(data): 654 if (units + 1) * UNIT != len(data): # the field does not count the 64-byte header (docs/bvh.md 3.1)
655 errs.append(f"totalSizeIn64BNodes {units} does not cover the {len(data)}-byte buffer") 655 errs.append(f"totalSizeIn64BNodes {units} does not cover the {len(data)}-byte buffer (64 * (field + 1) bytes)")
656 for name, off in (("offsetToNodes", nodes_off), ("offsetToElements", elements_off)): 656 for name, off in (("offsetToNodes", nodes_off), ("offsetToElements", elements_off)):
657 if off % UNIT or off > len(data): 657 if off % UNIT or off > len(data):
658 errs.append(f"{name} {off:#x} is unaligned or past the end") 658 errs.append(f"{name} {off:#x} is unaligned or past the end")