From 5055432943a3e8d43e261136b0f17132bc98ac4d Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Thu, 26 Nov 2026 20:24:59 +0000 Subject: [PATCH 01/44] startup: lower the FP32 box case of image_bvh_intersect_ray --- .../experiments/startup-gfx2hlsl-bvh-box32.md | 61 +++ .../python-linux/startup_gfx2hlsl_bvh.txt | 1 + tests/cmake/startup_gfx2hlsl_bvh.cmake | 14 + tests/startup_gfx2hlsl_bvh_check.py | 374 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 212 +++++++++- 5 files changed, 660 insertions(+), 2 deletions(-) create mode 100644 docs/experiments/startup-gfx2hlsl-bvh-box32.md create mode 100644 tests/checks/python-linux/startup_gfx2hlsl_bvh.txt create mode 100644 tests/cmake/startup_gfx2hlsl_bvh.cmake create mode 100644 tests/startup_gfx2hlsl_bvh_check.py diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md new file mode 100644 index 0000000000..928459f57f --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -0,0 +1,61 @@ +# First `image_bvh_intersect_ray` slice: FP32 box nodes + +`tools/startup/gfx2hlsl.py` now lowers the 32-bit `image_bvh_intersect_ray` (RDNA 2 MIMG opcode 230) for +one node form: the 128-byte FP32 box node, kind 5. The result is four child pointers, with `0xffffffff` for a +disabled child or a missed box. The helper performs the four slab tests, clips against `ray_extent`, and sorts +hits by entry distance only when bit 31 of the BVH T# is set. With sorting disabled it compacts hits in child +order, which is the order a traversal consumes the four results. + +The node layout is the one in Mesa 25.1.0 `src/amd/vulkan/bvh/bvh.h` (MIT): `children[4]` at bytes 0..15, +`coords[4][2][3]` at 16..111, and four reserved words at 112..127. The slab test follows Mesa +`radv_nir_rt_common.c` (MIT): inverse direction clamped to finite extremes, `tmin`/`tmax` from the three axes, +an inactive box whose `min.x` is NaN, `tmax >= max(0, tmin)`, `tmin < ray_extent`, and the five compare-exchange +stages that sort the four children. A child word of `0xffffffff` is a miss even when its stored box would hit. +The BVH T# fields are RDNA 2 ISA Table 49: base 39:0 (256-byte aligned), reserved 54:40, box growing 62:55, +box sorting 63, size 105:64, triangle return mode 120, big page 123 and type 8 at 127:124. + +## Accepted slice + +- compute stage only; +- `image_bvh_intersect_ray v[4], v[11], s[4]` with the packed address form (the disassembler prints `v[16:31]` + for the eleven consumed dwords); +- a constant inline T# built by four SGPR constants, type 8, base nonzero and 256-byte aligned, box growing zero, + size at least one 64-byte unit and below 4 GiB, and the node inside that size; +- a constant node pointer whose low three bits are 5, 128-byte aligned and inside the same 4 GiB address window; +- either value of the sort bit. + +The manifest names the node allocation with `srv bvh base 0x size 0x`. The host must bind a raw +`ByteAddressBuffer` at the base covering `(size + 1) * 64` bytes. That host binding is not part of this change. + +## Refused by name + +Triangle nodes (kind 0), 16-bit box nodes (kind 4), every other node kind, `image_bvh64_intersect_ray`, A16, +non-sequential addresses, a pixel or vertex stage, a node pointer that is not a straight-line constant, a T# +loaded at run time, a type other than 8, nonzero box growing, a misaligned base, an absolute base, a size that +does not cover the node, size bits above 4 GiB, and every reserved T# field. The checks assert that a refusal +emits no helper call and no destination VGPR assignment. + +## Evidence + +```text +python -B tests/startup_gfx2hlsl_bvh_check.py +``` + +The check compares the CPU box reference with the fixture in `tests/gfx1030_bvh_box/check.py` for five rays, +compares the emitted sort network with the same reference, checks the sort-bit negative control (word 0 changes +from `0x1d` to `0x25`), translates a synthetic constant-T# program and checks the four child results and the +manifest, and checks every refusal above. It also compiles the translated compute shader with DXC when one is +available; without DXC it prints `dxc compile: skip` and does not count that as a pass. + +```text +python -B tests/startup_gfx2hlsl_bvh_check.py dispatch warp +``` + +The dispatch mode compiles the same helper with a `RWByteAddressBuffer` in place of the bound +`ByteAddressBuffer`, writes the two synthetic nodes and five rays, and compares all twenty result words on a +Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.10068`). It also dispatches a mutant that leaves +missed child words in place; the case 2 word 0 must stop being `0xffffffff`. That control caught the first version +of this helper, which sorted the keys correctly but returned the original child pointer for a miss. + +This is a translator slice. It does not execute the native gfx1030 probe, does not bind the node buffer on a +D3D12 device, and does not establish any title behavior. diff --git a/tests/checks/python-linux/startup_gfx2hlsl_bvh.txt b/tests/checks/python-linux/startup_gfx2hlsl_bvh.txt new file mode 100644 index 0000000000..26480c9d8e --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_bvh.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_bvh_check.py diff --git a/tests/cmake/startup_gfx2hlsl_bvh.cmake b/tests/cmake/startup_gfx2hlsl_bvh.cmake new file mode 100644 index 0000000000..aaf68adc60 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_bvh.cmake @@ -0,0 +1,14 @@ +# gfx2hlsl image_bvh_intersect_ray FP32 box-node slice: translator controls, a DXC compile when +# one is available, and a WARP/hardware dispatch when offscreen_check is built. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_bvh COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bvh_check.py") +endif() +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_bvh_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bvh_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_bvh_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py new file mode 100644 index 0000000000..cc40ed6667 --- /dev/null +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -0,0 +1,374 @@ +"""image_bvh_intersect_ray: the FP32 box-node (kind 5) translation slice. + +The instruction is RDNA 2 MIMG opcode 230. This check covers the translator path and the +box model only: a constant inline BVH T#[12:15], an 11-dword packed address, a constant +node base whose low three bits are 5, and the four child results. Triangle nodes, 16-bit +box nodes, the 64-bit form, A16, NSA and every dynamic descriptor or node base are refused +by name before any HLSL is emitted. The CPU box reference is the one in +tests/gfx1030_bvh_box/check.py; the sort network is the five compare-exchange stages of +Mesa 25.1.0 radv_nir_rt_common.c (MIT). +""" +import math +import os +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tools" / "startup")) +sys.path.insert(0, str(HERE)) +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_compute_check as C # noqa: E402 + +INVALID = 0xffffffff +SORT_ENABLE = 1 << 31 +RESOURCE_TYPE = 1 << 31 +MASK = 0xffffffff +FLT_MAX = 3.4028234663852886e38 + + +def box(child, depth, x=-8): + return child, (x, -8, depth), (x + 16, 8, depth + 0.5) + + +NODES = { + 0: (box(0x25, 4), box(0x1d, 1), box(0x2d, 2, x=32), box(INVALID, 3)), + 256: (box(0x45, 7), box(0x3d, 5), box(0x35, 3), box(0x0d, 1)), +} +ORIGIN = (0.5, -0.5, -1.0) +FORWARD = (0.25, -0.125, 0.5) +RAYS = ( + ("sorted", 0, 19.0, ORIGIN, FORWARD, (0x1d, 0x25, INVALID, INVALID)), + ("clipped", 0, 6.0, ORIGIN, FORWARD, (0x1d, INVALID, INVALID, INVALID)), + ("all_miss", 0, 2.0, ORIGIN, FORWARD, (INVALID,) * 4), + ("all_four", 256, 19.0, ORIGIN, FORWARD, (0x0d, 0x35, 0x3d, 0x45)), + ("reverse", 0, 21.0, (0.0, 0.0, 10.0), (0.25, -0.125, -0.5), (0x25, 0x1d, INVALID, INVALID)), +) + +failures = [] + + +def check(label, ok, detail=""): + print("%s: %s" % (label, "ok" if ok else "MISMATCH"), flush=True) + if not ok: + failures.append(label) + if detail: + print(" " + detail) + + +def reference(nodes, extent, origin, direction, sort_boxes): + """The fixture reference: slab test, extent clip, compact misses, sort only when asked.""" + hits = [] + for child, lo, hi in nodes: + if child == INVALID: + continue + near, far = 0.0, extent + for lower, upper, start, step in zip(lo, hi, origin, direction, strict=True): + first, second = (lower - start) / step, (upper - start) / step + near, far = max(near, min(first, second)), min(far, max(first, second)) + if near <= far and near < extent: + hits.append((near, child)) + if sort_boxes: + hits.sort() + result = tuple(child for _, child in hits) + return result + (INVALID,) * (4 - len(result)) + + +def model(nodes, extent, origin, direction, sort_boxes): + """The emitted HLSL helper, transcribed: four slabs, keys, five compare-exchange stages.""" + inv = [max(-FLT_MAX, min(1.0 / c, FLT_MAX)) for c in direction] + items = [] + for child, lo, hi in nodes: + if child == INVALID: + items.append([INVALID, FLT_MAX]) + continue + bound0 = [(lo[i] - origin[i]) * inv[i] for i in range(3)] + bound1 = [(hi[i] - origin[i]) * inv[i] for i in range(3)] + tmin = max(min(bound0[i], bound1[i]) for i in range(3)) + tmax = min(max(bound0[i], bound1[i]) for i in range(3)) + hit = not math.isnan(lo[0]) and tmax >= max(0.0, tmin) and tmin < extent + if hit: + items.append([child, tmin if sort_boxes else 0.0]) + else: + items.append([INVALID, FLT_MAX]) + for a, b in ((0, 1), (2, 3), (0, 2), (1, 3), (1, 2)): + if items[b][1] < items[a][1]: + items[a], items[b] = items[b], items[a] + return tuple(item[0] for item in items) + + +def translate_program(*, node=0x05, sort_boxes=True, word0=0x00100000, word1=None, word2=0x0b, + word3=RESOURCE_TYPE, loaded_descriptor=False, modifier="", opcode="image_bvh_intersect_ray", + constant_node=True, stage_kind="cs"): + """A straight-line compute program with a constant inline T# and a constant node pointer.""" + if word1 is None: + word1 = SORT_ENABLE if sort_boxes else 0 + if stage_kind != "cs": + class Probe: + kind = stage_kind + try: + G.Stage.op_image_bvh_intersect_ray(Probe(), ("v[32:35]", "v[16:31]", "s[12:15]"), []) + except G.Unsupported as error: + return None, None, [str(error)] + return None, None, ["accepted outside compute"] + decoded = [] + at = 0 + + def add(name, asm, length=8): + nonlocal at + decoded.append((at, length, name, asm)) + at += length + + if loaded_descriptor: + add("s_mov_b32", "s_mov_b32 s10, s6") + add("s_mov_b32", "s_mov_b32 s11, 0") + add("s_load_dwordx4", "s_load_dwordx4 s[12:15], s[10:11], 0x0", 16) + add("s_waitcnt", "s_waitcnt lgkmcnt(0)", 4) + else: + for reg, word in ((12, word0), (13, word1), (14, word2), (15, word3)): + add("s_mov_b32", "s_mov_b32 s%d, 0x%08x" % (reg, word)) + for reg, word in ((16, node), (17, 0x41a00000), (18, 0x3f000000), (19, 0xbf000000), + (20, 0xbf800000), (21, 0x3e800000), (22, 0xbe000000), (23, 0x3f000000), + (24, 0x40800000), (25, 0xc1000000), (26, 0x40000000)): + source = "s4" if reg == 16 and not constant_node else "0x%08x" % word + add("v_mov_b32", "v_mov_b32 v%d, %s" % (reg, source)) + add(opcode, "%s v[32:35], v[16:31], s[12:15]%s" % (opcode, (" " + modifier) if modifier else "")) + add("s_endpgm", "s_endpgm", 4) + refusals = [] + pipe = G.ComputePipeline(b"", C.root_blob(), C.USER7, (1, 1, 1), refusals=refusals, decoded=decoded) + return pipe, pipe.hlsl_cs(), [reason for reason, _kind in refusals] + + +def controls(): + bad = None + for name, offset, extent, origin, direction, expected in RAYS: + actual = reference(NODES[offset], extent, origin, direction, True) + if actual != expected: + bad = (name, actual, expected) + break + check("CPU reference matches the gfx1030 box fixture", bad is None, str(bad)) + + bad = None + for name, offset, extent, origin, direction, expected in RAYS: + actual = model(NODES[offset], extent, origin, direction, True) + if actual != expected: + bad = (name, actual, expected) + break + check("emitted sort network matches the CPU reference", bad is None, str(bad)) + + # Negative control: sort disabled keeps child order. The sorted ray's first word changes. + unsorted = reference(NODES[0], 19.0, ORIGIN, FORWARD, False) + sorted_result = reference(NODES[0], 19.0, ORIGIN, FORWARD, True) + check("sort bit negative control changes word 0", + unsorted[0] == 0x25 and sorted_result[0] == 0x1d, str((unsorted, sorted_result))) + check("model without the sort bit matches the unsorted reference", + model(NODES[0], 19.0, ORIGIN, FORWARD, False) == unsorted, + str((model(NODES[0], 19.0, ORIGIN, FORWARD, False), unsorted))) + check("all-miss result is four 0xffffffff words", + reference(NODES[0], 2.0, ORIGIN, FORWARD, True) == (INVALID,) * 4, "") + + pipe, hlsl, refusals = translate_program() + check("constant box32 program translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + manifest = pipe.manifest() + check("manifest names the node allocation", "srv 0 bvh base 0x100000 size 0xb" in manifest, manifest) + check("HLSL declares the node buffer", "ByteAddressBuffer r0 : register(t0);" in hlsl, "") + check("HLSL contains the four-result helper", + "uint4 x2w_bvh_intersect_box32" in hlsl and "x2w_bvh_box32_slot" in hlsl, "") + check("the call carries the sort-enabled T# word and four child results", + "0x80000000u" in hlsl and all("v%d = bt" % reg in hlsl for reg in range(32, 36)), + "") + call_line = next(line for line in hlsl.splitlines() if "x2w_bvh_intersect_box32(r0" in line) + check("constant T# passes literals, not descriptor SGPRs", + "s12" not in call_line and "s13" not in call_line, call_line) + + pipe, hlsl, refusals = translate_program(sort_boxes=False) + check("sort-disabled program translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + check("sort-disabled call uses a zero sort word", "0x00000000u" in hlsl, "") + + # Every refusal must happen before a helper call or a result VGPR is emitted. + cases = [ + ("triangle node", dict(node=0x00), "triangle node (kind 0)"), + ("16-bit box node", dict(node=0x04), "16-bit box node (kind 4)"), + ("unknown node kind", dict(node=0x06), "node kind 6"), + ("unaligned node", dict(node=0x0d), "not an aligned 128-byte node"), + ("non-constant node", dict(constant_node=False), "non-constant node base"), + ("64-bit form", dict(opcode="image_bvh64_intersect_ray"), "image_bvh64_intersect_ray"), + ("A16", dict(modifier="a16"), "modifier a16"), + ("NSA address", dict(modifier=""), "non-sequential"), + ("loaded descriptor", dict(loaded_descriptor=True), "loaded at run time"), + ("descriptor type", dict(word3=0x60000000), "descriptor type 6 is not 8"), + ("box growing", dict(word1=SORT_ENABLE | (2 << 23)), "box growing amount 2"), + ("base alignment", dict(word0=0x00100008), "not 256-byte aligned"), + ("size zero", dict(word2=0), "does not cover a 128-byte node"), + ("node outside size", dict(node=0x25, word2=3), "outside descriptor size"), + ("absolute base", dict(word0=0, word1=0), "absolute node base"), + ("size high bits", dict(word3=RESOURCE_TYPE | 0x100), "size above 4 GiB"), + ] + for label, kwargs, reason in cases: + if label == "NSA address": + # A non-sequential address is a text form the packed decoder never prints. + pipe, hlsl, refusals = None, None, [] + try: + G.Stage.op_image_bvh_intersect_ray( + type("P", (), {"kind": "cs", "const_u32": lambda self, tok: 5})(), + ("v[32:35]", "[v0, v2, v4, v6, v8, v10, v12, v14, v16, v18, v20]", "s[12:15]"), []) + except G.Unsupported as error: + refusals = [str(error)] + else: + pipe, hlsl, refusals = translate_program(**kwargs) + ok = len(refusals) == 1 and reason in refusals[0] + check("refuses %s" % label, ok, str(refusals)) + if hlsl is not None: + check(" no partial output for %s" % label, + "uint4 bt" not in hlsl and "x2w_bvh_intersect_box32(r" not in hlsl, "") + + pipe, hlsl, refusals = translate_program(stage_kind="ps") + check("refuses a pixel stage", len(refusals) == 1 and "outside a compute stage" in refusals[0], str(refusals)) + + +def find_dxc(): + named = os.environ.get("X2W_DXC") + if named and Path(named).is_file(): + return str(Path(named)) + found = shutil.which("dxc") + if found: + return found + kits = os.environ.get("ProgramFiles(x86)", "") + if kits: + candidates = sorted((Path(kits) / "Windows Kits" / "10" / "bin").glob("*/x64/dxc.exe"), reverse=True) + if candidates: + return str(candidates[0]) + return None + + +def compile_check(hlsl): + dxc = find_dxc() + if dxc is None: + print("dxc compile: skip (no dxc on this host)") + return None + with tempfile.TemporaryDirectory(dir=ROOT / "out" if (ROOT / "out").is_dir() else None) as temporary: + source = Path(temporary) / "bvh_box32.hlsl" + source.write_text(hlsl, encoding="ascii") + result = subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", str(source.with_suffix(".cso")), str(source)], + capture_output=True, text=True) + if result.returncode or result.stderr: + check("dxc compiles the translated helper", False, result.stderr or "exit %d" % result.returncode) + return False + print("dxc compile: ok (%s)" % dxc) + return True + + + + +def ffloat(value): + return "asfloat(0x%08xu)" % struct.unpack("> 3) | 5, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), + ffloat(origin[2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) + for word in range(4): + lines.append(" data.Store(%du, r%d.%s);" % (512 + 16 * case + 4 * word, case, "xyzw"[word])) + lines.append("}") + return "\n".join(lines) + "\n" + + +def run_dispatch(dxc, runner, adapter, directory, mutate=False): + name = "bvh_dispatch_mut" if mutate else "bvh_dispatch" + source = directory / (name + ".hlsl") + cso = directory / (name + ".cso") + output = directory / (name + ".bin") + source.write_text(dispatch_hlsl(mutate), encoding="ascii") + compiled = subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + capture_output=True, text=True) + if compiled.returncode or compiled.stderr: + raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", "592", str(output)], + capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return 77, None + if result.returncode or result.stderr: + raise AssertionError(result.stderr or "offscreen_check exited with %d" % result.returncode) + data = output.read_bytes() + return 0, struct.unpack("<%dI" % (len(data) // 4), data) + + +def check_dispatch(dxc, runner, adapter): + controls() + if not dxc or not runner: + print("dispatch: skip (no dxc or offscreen_check)") + return 77 + out = ROOT / "out" + out.mkdir(exist_ok=True) + with tempfile.TemporaryDirectory(dir=out) as temporary: + directory = Path(temporary) + status, words = run_dispatch(dxc, runner, adapter, directory) + if status == 77: + print("dispatch: skip (adapter unavailable)") + return 77 + for case, (_name, _offset, _extent, _origin, _direction, expected) in enumerate(RAYS): + got = tuple(words[128 + 4 * case:132 + 4 * case]) + check("dispatch case %d %s" % (case, _name), got == expected, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in expected])) + status, mutant = run_dispatch(dxc, runner, adapter, directory, mutate=True) + if status == 77: + print("dispatch control: skip (adapter unavailable)") + return 77 + changed = mutant[128:132] + check("dispatch miss-fill control decays case 2", tuple(changed) != (INVALID,) * 4, + "got %s" % ["%08x" % w for w in changed]) + if failures: + print("FAILED: %s" % ", ".join(failures)) + return 1 + print("dispatch: all ok on %s" % adapter) + return 0 + +def main(): + if len(sys.argv) == 5 and sys.argv[1] == "dispatch": + return check_dispatch(sys.argv[2], sys.argv[3], sys.argv[4]) + if len(sys.argv) != 1: + sys.exit(__doc__) + controls() + pipe, hlsl, refusals = translate_program() + assert not refusals, refusals + compile_check(hlsl) + if failures: + print("FAILED: %s" % ", ".join(failures)) + return 1 + print("startup gfx2hlsl bvh box32: all ok") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 489148b039..3e1db887b5 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2293,6 +2293,7 @@ def __init__(self, pipe, kind, code, refusals=None, decoded=None): first_refusal = len(refusals) if refusals is not None else 0 while True: self.lines = [] # body statements (per block) + self.vconst = {} # VGPR -> literal 32-bit value while the program is straight-line self.sym = {} # scalar register -> symbolic value self.used_s, self.used_v = set(), set() self.used_atomic = set() @@ -2697,6 +2698,13 @@ def set_v(self, n, expr, *, low16_only=False, align4=False): else: self.align4_v.discard(n) self.last_v = (n, expr) + vconst = getattr(self, 'vconst', None) + if isinstance(vconst, dict): + literal = re.fullmatch(r'0x([0-9a-fA-F]{8})u', expr) + if literal: + vconst[n] = int(literal.group(1), 16) + else: + vconst.pop(n, None) if low16_only: if not isinstance(self.low16_only_v, set): self.low16_only_v = set() @@ -3523,6 +3531,7 @@ def translate(self): self.address_carry_reader = None uniform_vcc_compares = set() self.lines = [] + self.vconst = {} self.blocks = [] # (offset, [lines], terminator) self.sym = dict(init_sym) self.exec_known = init_exec_known @@ -7497,6 +7506,115 @@ def fixed_table_image(self, operand, name): raise Unsupported('%s through a modified image descriptor' % name) return self.descriptor(operand) + def bvh_descriptor(self, tok): + """The binding key and literal words of an inline constant BVH T#. + + The table-name form and the run-time descriptor are deliberately outside this first slice: the + host binding for a T# read from a descriptor heap is not part of this change, and passing the + four words as uninitialized SGPRs would read address zero. A constant T# built by four s_mov_b32 + instructions is fully proved here, so the emitted helper receives literals and the manifest can + name the node allocation by its base and size. + """ + name = 'image_bvh_intersect_ray' + r = reg_range(tok) + if not r or r[0] != 's' or r[2] - r[1] != 3: + raise Unsupported('%s descriptor %s is not four consecutive SGPRs' % (name, tok)) + values = [self.is_const(n) for n in range(r[1], r[2] + 1)] + if any(value is None for value in values): + first = self.sym.get(r[1]) + if first and first[0] == 'desc': + raise Unsupported('%s descriptor %s is loaded at run time: only a constant inline T# is ' + 'lowered in this slice' % (name, tok)) + raise Unsupported('%s descriptor %s is not four constant SGPRs' % (name, tok)) + words = ['0x%08xu' % (value & 0xffffffff) for value in values] + base = ((values[1] & 0xff) << 32) | values[0] + return (('bvhbase', base, values[2]), None), words, values + + def op_image_bvh_intersect_ray(self, ops, mods): + """Ray/box intersection for the 128-byte FP32 box node (kind 5). + + RDNA 2 ISA section 8.2.10 and Table 48: VDATA is four result dwords, VADDR is 11 dwords + (node pointer, extent, origin xyz, direction xyz, inverse direction xyz) and SRSRC is the + four-word BVH T# of Table 49. This first slice accepts only a straight-line compute program + with a constant node base, a constant inline T# and a node whose kind bits are 5. + The descriptor base binds a ByteAddressBuffer at the 256-byte-aligned allocation; the node + pointer is an offset in 8-byte units from that base. The emitted helper performs the four + slab tests, clips against extent, compacts misses to 0xffffffff, and sorts by entry distance + only when the descriptor's box-sorting enable bit is set. Triangle nodes, 16-bit box nodes, + the 64-bit form, A16, non-sequential addresses and every other node kind are refused by name. + """ + name = 'image_bvh_intersect_ray' + if self.kind != 'cs': + raise Unsupported('%s outside a compute stage' % name) + if mods: + raise Unsupported('%s modifier %s' % (name, ' '.join(mods))) + if len(ops) != 3: + raise Unsupported('%s with %d operands, expected 3' % (name, len(ops))) + dst = reg_range(ops[0]) + if not dst or dst[0] != 'v' or dst[2] - dst[1] != 3 or dst[2] > 255: + raise Unsupported('%s destination %s is not four consecutive VGPRs' % (name, ops[0])) + if ops[1].startswith('['): + raise Unsupported('%s non-sequential address %s is not lowered' % (name, ops[1])) + addr = reg_range(ops[1]) + if not addr or addr[0] != 'v' or addr[2] > 255 or addr[2] - addr[1] + 1 not in (11, 16): + raise Unsupported('%s address %s is not an 11-dword VGPR range' % (name, ops[1])) + cs = ['v%d' % n for n in range(addr[1], addr[1] + 11)] + node = self.const_u32(cs[0]) + node_reg = reg_range(cs[0]) + if node is None and node_reg and node_reg[0] == 'v' and not getattr(self, 'has_branches', True): + node = getattr(self, 'vconst', {}).get(node_reg[1]) + if node is None: + raise Unsupported('%s non-constant node base %s' % (name, cs[0])) + kind = node & 7 + if kind == 4: + raise Unsupported('%s 16-bit box node (kind 4) is not lowered' % name) + if kind == 0: + raise Unsupported('%s triangle node (kind 0) is not lowered' % name) + if kind != 5: + raise Unsupported('%s node kind %d is not lowered' % (name, kind)) + node_offset = (node & 0xfffffff8) << 3 + if node_offset > 0xffffff80 or node_offset & 0x7f: + raise Unsupported('%s node base %#x is not an aligned 128-byte node' % (name, node_offset)) + key, words, vals = self.bvh_descriptor(ops[2]) + if vals[0] is not None and vals[0] & 0xff: + raise Unsupported('%s descriptor base is not 256-byte aligned' % name) + if vals[1] is not None: + if vals[1] & 0x7f800000: + raise Unsupported('%s box growing amount %d is not lowered' % (name, (vals[1] >> 23) & 0xff)) + if vals[1] & 0x007fff00: + raise Unsupported('%s descriptor reserved word 1 %#x' % (name, vals[1])) + if vals[3] is not None: + if (vals[3] >> 28) & 0xf != 8: + raise Unsupported('%s descriptor type %d is not 8' % (name, (vals[3] >> 28) & 0xf)) + if vals[3] & 0x0fffffff: + raise Unsupported('%s descriptor size above 4 GiB or reserved word 3 %#x' % (name, vals[3])) + if vals[0] is not None and vals[1] is not None and ((vals[1] & 0xff) << 32 | vals[0]) == 0: + raise Unsupported('%s absolute node base is not lowered' % name) + if vals[2] is not None: + if vals[2] < 1 or vals[2] >= 0x04000000: + raise Unsupported('%s descriptor size %d does not cover a 128-byte node' % (name, vals[2])) + if (node_offset >> 6) + 1 > vals[2]: + raise Unsupported('%s node base %#x is outside descriptor size %d' % (name, node_offset, vals[2])) + extent = self.f(cs[1]) + origin = [self.f(cs[2 + i]) for i in range(3)] + [self.f(cs[5 + i]) for i in range(3)] # the instruction consumes ray_dir; the helper uses inv_dir + inv_dir = [self.f(cs[8 + i]) for i in range(3)] + if vals[1] is not None: + sort = '0x80000000u' if vals[1] & 0x80000000 else '0x00000000u' + else: + sort = '(%s & 0x80000000u)' % words[1] + res = self.pipe.resource(key, 'bvh') + self.pipe.uses_bvh = True + call = 'x2w_bvh_intersect_box32(%s, 0x%08xu, %s, %s, %s, %s, %s, float3(%s, %s, %s), float3(%s, %s, %s))' % ( + res, node, words[0], sort, words[2], words[3], extent, + origin[0], origin[1], origin[2], inv_dir[0], inv_dir[1], inv_dir[2]) + self.emit('uint4 bt%x = %s;' % (self.pc or 0, call)) + for i in range(4): + self.set_v(dst[1] + i, 'bt%x.%s' % (self.pc or 0, 'xyzw'[i])) + + def op_image_bvh64_intersect_ray(self, ops, mods): + raise Unsupported('image_bvh64_intersect_ray: only the 32-bit image_bvh_intersect_ray is lowered') + def op_image_store(self, ops, mods): """Write a full 2D texel or, for compute, a full 2D-array texel. @@ -10167,9 +10285,92 @@ def read(fmt, data, offset): VERIFIED_SINT_RTVS = frozenset((4, 14, 18, 32, 38, 43, 52, 59, 64)) +BVH_HELPERS = ( + 'static const uint X2W_BVH_MISS = 0xffffffffu;', + # The 128-bit BVH T# (RDNA 2 ISA Table 49): base 39:0, box growing 62:55, sort enable 63, + # size 105:64 and type 8 at 127:124. This slice binds a ByteAddressBuffer at the base and + # keeps the descriptor in a 32-bit address window, so the size-high ten bits and every + # reserved field must be zero. A zero base selects the absolute pointer form, which this + # slice does not bind, so it is refused here as a miss rather than read at address zero. + 'bool x2w_bvh_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', + ' return (word0 & 0x000000ffu) == 0u && (word1 & 0x7fffff00u) == 0u &&', + ' word3 == 0x80000000u && word2 >= 1u && word2 < 0x04000000u &&', + ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', + '}', + # One FP32 box from a radv_bvh_box32_node (Mesa 25.1.0 bvh/bvh.h, MIT): children[4] at + # bytes 0..15, coords[4][2][3] at 16..111 (lo then hi per child) and reserved at 112..127. + 'float x2w_bvh_box32_slot(ByteAddressBuffer nodes, uint node_offset, uint index, float extent,', + ' float3 origin, float3 inv_dir, out bool hit) {', + ' uint at = node_offset + 16u + 24u * index;', + ' float3 lo = float3(asfloat(nodes.Load(at)), asfloat(nodes.Load(at + 4u)),', + ' asfloat(nodes.Load(at + 8u)));', + ' float3 hi = float3(asfloat(nodes.Load(at + 12u)), asfloat(nodes.Load(at + 16u)),', + ' asfloat(nodes.Load(at + 20u)));', + ' float3 bound0 = (lo - origin) * inv_dir;', + ' float3 bound1 = (hi - origin) * inv_dir;', + ' float tmin = max(max(min(bound0.x, bound1.x), min(bound0.y, bound1.y)),', + ' min(bound0.z, bound1.z));', + ' float tmax = min(min(max(bound0.x, bound1.x), max(bound0.y, bound1.y)),', + ' max(bound0.z, bound1.z));', + # A NaN in min.x marks an inactive box (Vulkan inactive primitive rule; Mesa tests NaN != NaN). + ' bool active = (asuint(lo.x) & 0x7fffffffu) <= 0x7f800000u;', + ' hit = active && tmax >= max(0.0, tmin) && tmin < extent;', + ' return hit ? tmin : 3.402823466e+38;', + '}', + # The five compare-exchange stages of Mesa radv_nir_rt_common.c: equal keys do not swap, + # so misses (key +inf) sink to the end and unsorted hits keep their child order. + 'void x2w_bvh_sort_pair(inout uint ia, inout uint ib, inout float ka, inout float kb) {', + ' if (kb < ka) { uint ti = ia; ia = ib; ib = ti; float tk = ka; ka = kb; kb = tk; }', + '}', + 'uint4 x2w_bvh_intersect_box32(ByteAddressBuffer nodes, uint node, uint word0, uint word1,', + ' uint word2, uint word3, float extent, float3 origin,', + ' float3 inv_dir) {', + ' uint4 miss = uint4(X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS);', + ' if ((node & 7u) != 5u || !x2w_bvh_descriptor_ok(word0, word1, word2, word3)) return miss;', + ' uint offset = (node & 0xfffffff8u) << 3u;', + ' if ((offset >> 6u) + 1u > word2) return miss;', + # Mesa clamps the inverse direction so a zero direction component cannot turn 0 * inf + # into NaN. The box test then follows the software reference exactly. + ' inv_dir = clamp(inv_dir, -3.402823466e+38, 3.402823466e+38);', + ' bool h0, h1, h2, h3;', + ' float d0 = x2w_bvh_box32_slot(nodes, offset, 0u, extent, origin, inv_dir, h0);', + ' float d1 = x2w_bvh_box32_slot(nodes, offset, 1u, extent, origin, inv_dir, h1);', + ' float d2 = x2w_bvh_box32_slot(nodes, offset, 2u, extent, origin, inv_dir, h2);', + ' float d3 = x2w_bvh_box32_slot(nodes, offset, 3u, extent, origin, inv_dir, h3);', + ' bool sort_boxes = (word1 & 0x80000000u) != 0u;', + ' uint c0 = nodes.Load(offset);', + ' uint c1 = nodes.Load(offset + 4u);', + ' uint c2 = nodes.Load(offset + 8u);', + ' uint c3 = nodes.Load(offset + 12u);', + # A disabled child stores 0xffffffff and must not enter the hit list even if its box is valid. + ' h0 = h0 && c0 != X2W_BVH_MISS;', + ' h1 = h1 && c1 != X2W_BVH_MISS;', + ' h2 = h2 && c2 != X2W_BVH_MISS;', + ' h3 = h3 && c3 != X2W_BVH_MISS;', + ' c0 = h0 ? c0 : X2W_BVH_MISS;', + ' c1 = h1 ? c1 : X2W_BVH_MISS;', + ' c2 = h2 ? c2 : X2W_BVH_MISS;', + ' c3 = h3 ? c3 : X2W_BVH_MISS;', + # A disabled sort uses one key for every hit: the network then only compacts misses, + # while an enabled sort orders the hits by entry distance. + ' float k0 = h0 ? (sort_boxes ? d0 : 0.0) : 3.402823466e+38;', + ' float k1 = h1 ? (sort_boxes ? d1 : 0.0) : 3.402823466e+38;', + ' float k2 = h2 ? (sort_boxes ? d2 : 0.0) : 3.402823466e+38;', + ' float k3 = h3 ? (sort_boxes ? d3 : 0.0) : 3.402823466e+38;', + ' x2w_bvh_sort_pair(c0, c1, k0, k1);', + ' x2w_bvh_sort_pair(c2, c3, k2, k3);', + ' x2w_bvh_sort_pair(c0, c2, k0, k2);', + ' x2w_bvh_sort_pair(c1, c3, k1, k3);', + ' x2w_bvh_sort_pair(c1, c2, k1, k2);', + ' return uint4(c0, c1, c2, c3);', + '}', +) + + class Pipeline: vertex_kind = 'vs' uses_pack16_rne = False + uses_bvh = False uses_gather_2d_lod = False uses_store_d16_x = False uses_sad = () @@ -10208,6 +10409,7 @@ def _init_pixel_context(self, root_blob, sampler_heap=None, rtv_formats=(), ps_h self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False self.uses_pack16_rne = False + self.uses_bvh = False self.uses_gather_2d_lod = False self.uses_store_d16_x = False self.uses_sad = set() @@ -10427,8 +10629,10 @@ def common(self): 'uint ldu(ByteAddressBuffer b, uint a) { uint k = (a & 3) * 8, lo = b.Load(a & ~3u); if (k == 0) return lo; ' 'return (lo >> k) | (b.Load((a & ~3u) + 4) << (32 - k)); }', 'cbuffer entry : register(b0) { %s };' % ' '.join('uint ud%d;' % i for i in range(len(self.uds)))] + if self.uses_bvh: + out.extend(BVH_HELPERS) for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): - out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'tex1d': 'Texture1D', 'tex2d': 'Texture2D', 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D'}[r['kind']], r['index'], r['index'])) + out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'bvh': 'ByteAddressBuffer', 'tex1d': 'Texture1D', 'tex2d': 'Texture2D', 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D'}[r['kind']], r['index'], r['index'])) for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): out.append('%s %s%d : register(u%d);' % ({'tex2d': 'RWTexture2D', 'tex2da': 'RWTexture2DArray', 'raw': 'RWByteAddressBuffer'}[r['kind']], 'u' if r['kind'] == 'raw' else 'w', r['index'], r['index'])) for key, i in self.samplers.items(): @@ -10754,6 +10958,7 @@ def manifest(self): for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): source, off = key where = {'table': 'table %d %d' % (source[1] if len(source) > 1 else 0, off or 0), 'vbtab': 'vb %d' % ((off or 0) // 16), + 'bvhbase': 'base 0x%x size 0x%x' % (source[1], source[2]), 'root': 'root %d' % (source[1] if len(source) > 1 else 0)}.get(source[0]) if where is None: raise Unsupported('resource through %s' % (source,)) @@ -10805,6 +11010,7 @@ def __init__(self, cs_code, root_blob, rsrc2, group, sampler_heap=None, refusals self.uses_sampler_heap = False self.uses_gather_2d_lod = False self.uses_store_d16_x = False + self.uses_bvh = False self.uses_sad = set() self.resources, self.uavs, self.samplers, self.uds = {}, {}, {}, [] self.notes, self.modified, self.other_modified = set(), set(), set() # other: unproved descriptor writes @@ -10848,7 +11054,9 @@ def manifest(self): lines = ['x2w-manifest 2', 'stage cs', 'group %d %d %d' % self.group, 'ud %d' % len(self.uds)] lines += ['udsrc %d %s' % (i, ' '.join(str(x) for x in source)) for i, source in enumerate(self.uds)] for (source, off), r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): - if source[0] == 'table': + if source[0] == 'bvhbase': + where = 'base 0x%x size 0x%x' % (source[1], source[2]) + elif source[0] == 'table': where = 'table %d %d' % (source[1], off or 0) elif source[0] == 'root': where = 'root %d' % source[1] From 2ec454f9ea80d5d22366692da0302f7af5dba834 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Thu, 26 Nov 2026 20:39:24 +0000 Subject: [PATCH 02/44] startup: keep non-BVH resource manifests from reading a third field --- tools/startup/gfx2hlsl.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 3e1db887b5..eae274393b 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -10957,9 +10957,12 @@ def manifest(self): lines.append('udsrc %d %s' % (i, ' '.join(str(x) for x in source))) for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): source, off = key - where = {'table': 'table %d %d' % (source[1] if len(source) > 1 else 0, off or 0), 'vbtab': 'vb %d' % ((off or 0) // 16), - 'bvhbase': 'base 0x%x size 0x%x' % (source[1], source[2]), - 'root': 'root %d' % (source[1] if len(source) > 1 else 0)}.get(source[0]) + if source[0] == 'bvhbase': + where = 'base 0x%x size 0x%x' % (source[1], source[2]) + else: + where = {'table': 'table %d %d' % (source[1] if len(source) > 1 else 0, off or 0), + 'vbtab': 'vb %d' % ((off or 0) // 16), + 'root': 'root %d' % (source[1] if len(source) > 1 else 0)}.get(source[0]) if where is None: raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) From 34a2c5c17db50be0f66f33595e5ab54ad058517a Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Thu, 26 Nov 2026 21:38:05 +0000 Subject: [PATCH 03/44] startup: lower binary16 box nodes in image_bvh_intersect_ray --- .../experiments/startup-gfx2hlsl-bvh-box32.md | 31 +++++--- tests/startup_gfx2hlsl_bvh_check.py | 39 ++++++++-- tools/startup/gfx2hlsl.py | 74 ++++++++++++++++--- 3 files changed, 115 insertions(+), 29 deletions(-) diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md index 928459f57f..0f1bf29eec 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-box32.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -1,10 +1,10 @@ -# First `image_bvh_intersect_ray` slice: FP32 box nodes +# First `image_bvh_intersect_ray` slice: FP32 and binary16 box nodes `tools/startup/gfx2hlsl.py` now lowers the 32-bit `image_bvh_intersect_ray` (RDNA 2 MIMG opcode 230) for -one node form: the 128-byte FP32 box node, kind 5. The result is four child pointers, with `0xffffffff` for a -disabled child or a missed box. The helper performs the four slab tests, clips against `ray_extent`, and sorts -hits by entry distance only when bit 31 of the BVH T# is set. With sorting disabled it compacts hits in child -order, which is the order a traversal consumes the four results. +the two box-node forms: the 128-byte FP32 node (kind 5) and the 64-byte binary16 node (kind 4). The result is +four child pointers, with `0xffffffff` for a disabled child or a missed box. The helper performs the four slab +tests, clips against `ray_extent`, and sorts hits by entry distance only when bit 31 of the BVH T# is set. With +sorting disabled it compacts hits in child order, which is the order a traversal consumes the four results. The node layout is the one in Mesa 25.1.0 `src/amd/vulkan/bvh/bvh.h` (MIT): `children[4]` at bytes 0..15, `coords[4][2][3]` at 16..111, and four reserved words at 112..127. The slab test follows Mesa @@ -14,6 +14,10 @@ stages that sort the four children. A child word of `0xffffffff` is a miss even The BVH T# fields are RDNA 2 ISA Table 49: base 39:0 (256-byte aligned), reserved 54:40, box growing 62:55, box sorting 63, size 105:64, triangle return mode 120, big page 123 and type 8 at 127:124. +The binary16 node has the same four child words at bytes 0..15 and four boxes of six binary16 values at +16..63. `f16tof32` widens each bound exactly before the same slab test. The inactive-box marker is still a NaN +in `min.x`. + ## Accepted slice - compute stage only; @@ -21,15 +25,17 @@ box sorting 63, size 105:64, triangle return mode 120, big page 123 and type 8 a for the eleven consumed dwords); - a constant inline T# built by four SGPR constants, type 8, base nonzero and 256-byte aligned, box growing zero, size at least one 64-byte unit and below 4 GiB, and the node inside that size; -- a constant node pointer whose low three bits are 5, 128-byte aligned and inside the same 4 GiB address window; +- a constant node pointer whose low three bits are 4 (64-byte aligned) or 5 (128-byte aligned) and inside the + same 4 GiB address window; - either value of the sort bit. -The manifest names the node allocation with `srv bvh base 0x size 0x`. The host must bind a raw -`ByteAddressBuffer` at the base covering `(size + 1) * 64` bytes. That host binding is not part of this change. +The manifest names the node allocation with `srv bvh base 0x size 0x`. The size is in 64-byte +units; a binary16 node covers one unit and an FP32 node two. The host must bind a raw `ByteAddressBuffer` at +the base covering `size * 64` bytes. That host binding is not part of this change. ## Refused by name -Triangle nodes (kind 0), 16-bit box nodes (kind 4), every other node kind, `image_bvh64_intersect_ray`, A16, +Triangle nodes (kinds 0..3), every other node kind, `image_bvh64_intersect_ray`, A16, non-sequential addresses, a pixel or vertex stage, a node pointer that is not a straight-line constant, a T# loaded at run time, a type other than 8, nonzero box growing, a misaligned base, an absolute base, a size that does not cover the node, size bits above 4 GiB, and every reserved T# field. The checks assert that a refusal @@ -43,9 +49,10 @@ python -B tests/startup_gfx2hlsl_bvh_check.py The check compares the CPU box reference with the fixture in `tests/gfx1030_bvh_box/check.py` for five rays, compares the emitted sort network with the same reference, checks the sort-bit negative control (word 0 changes -from `0x1d` to `0x25`), translates a synthetic constant-T# program and checks the four child results and the -manifest, and checks every refusal above. It also compiles the translated compute shader with DXC when one is -available; without DXC it prints `dxc compile: skip` and does not count that as a pass. +from `0x1d` to `0x25`), rounds the bounds to binary16 and checks the same box result, translates a synthetic +constant-T# program for each node kind and checks the four child results and the manifest, and checks every +refusal above. It also compiles the translated compute shader with DXC when one is available; without DXC it +prints `dxc compile: skip` and does not count that as a pass. ```text python -B tests/startup_gfx2hlsl_bvh_check.py dispatch warp diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py index cc40ed6667..e72a2be0ac 100644 --- a/tests/startup_gfx2hlsl_bvh_check.py +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -1,10 +1,10 @@ -"""image_bvh_intersect_ray: the FP32 box-node (kind 5) translation slice. +"""image_bvh_intersect_ray: the FP32 and binary16 box-node translation slice. The instruction is RDNA 2 MIMG opcode 230. This check covers the translator path and the box model only: a constant inline BVH T#[12:15], an 11-dword packed address, a constant -node base whose low three bits are 5, and the four child results. Triangle nodes, 16-bit -box nodes, the 64-bit form, A16, NSA and every dynamic descriptor or node base are refused -by name before any HLSL is emitted. The CPU box reference is the one in +node base whose low three bits are 4 (binary16) or 5 (FP32), and the four child results. +Triangle nodes, the 64-bit form, A16, NSA and every dynamic descriptor or node base are +refused by name before any HLSL is emitted. The CPU box reference is the one in tests/gfx1030_bvh_box/check.py; the sort network is the five compare-exchange stages of Mesa 25.1.0 radv_nir_rt_common.c (MIT). """ @@ -102,6 +102,16 @@ def model(nodes, extent, origin, direction, sort_boxes): return tuple(item[0] for item in items) +def half_nodes(nodes): + """The same nodes with every bound rounded to binary16 before the box test.""" + quantized = [] + for child, lo, hi in nodes: + def q(value): + return struct.unpack(" 0xffffff80 or node_offset & 0x7f: - raise Unsupported('%s node base %#x is not an aligned 128-byte node' % (name, node_offset)) + if node_offset > (0xffffffc0 if half_box else 0xffffff80) or node_offset & (0x3f if half_box else 0x7f): + raise Unsupported('%s node base %#x is not an aligned %u-byte node' % (name, node_offset, node_bytes)) key, words, vals = self.bvh_descriptor(ops[2]) if vals[0] is not None and vals[0] & 0xff: raise Unsupported('%s descriptor base is not 256-byte aligned' % name) @@ -7592,7 +7592,7 @@ def op_image_bvh_intersect_ray(self, ops, mods): raise Unsupported('%s absolute node base is not lowered' % name) if vals[2] is not None: if vals[2] < 1 or vals[2] >= 0x04000000: - raise Unsupported('%s descriptor size %d does not cover a 128-byte node' % (name, vals[2])) + raise Unsupported('%s descriptor size %d does not cover the node' % (name, vals[2])) if (node_offset >> 6) + 1 > vals[2]: raise Unsupported('%s node base %#x is outside descriptor size %d' % (name, node_offset, vals[2])) extent = self.f(cs[1]) @@ -7605,7 +7605,8 @@ def op_image_bvh_intersect_ray(self, ops, mods): sort = '(%s & 0x80000000u)' % words[1] res = self.pipe.resource(key, 'bvh') self.pipe.uses_bvh = True - call = 'x2w_bvh_intersect_box32(%s, 0x%08xu, %s, %s, %s, %s, %s, float3(%s, %s, %s), float3(%s, %s, %s))' % ( + call = '%s(%s, 0x%08xu, %s, %s, %s, %s, %s, float3(%s, %s, %s), float3(%s, %s, %s))' % ( + 'x2w_bvh_intersect_box16' if half_box else 'x2w_bvh_intersect_box32', res, node, words[0], sort, words[2], words[3], extent, origin[0], origin[1], origin[2], inv_dir[0], inv_dir[1], inv_dir[2]) self.emit('uint4 bt%x = %s;' % (self.pc or 0, call)) @@ -10317,6 +10318,24 @@ def read(fmt, data, offset): ' hit = active && tmax >= max(0.0, tmin) && tmin < extent;', ' return hit ? tmin : 3.402823466e+38;', '}', + # One binary16 box from a radv_bvh_box16_node: children[4] at 0..15, coords[4][2][3] at + # 16..63, six binary16 values per child. The half values widen exactly to binary32. + 'float x2w_bvh_box16_slot(ByteAddressBuffer nodes, uint node_offset, uint index, float extent,', + ' float3 origin, float3 inv_dir, out bool hit) {', + ' uint at = node_offset + 16u + 12u * index;', + ' uint h0 = nodes.Load(at), h1 = nodes.Load(at + 4u), h2 = nodes.Load(at + 8u);', + ' float3 lo = float3(f16tof32(h0), f16tof32(h0 >> 16u), f16tof32(h1));', + ' float3 hi = float3(f16tof32(h1 >> 16u), f16tof32(h2), f16tof32(h2 >> 16u));', + ' float3 bound0 = (lo - origin) * inv_dir;', + ' float3 bound1 = (hi - origin) * inv_dir;', + ' float tmin = max(max(min(bound0.x, bound1.x), min(bound0.y, bound1.y)),', + ' min(bound0.z, bound1.z));', + ' float tmax = min(min(max(bound0.x, bound1.x), max(bound0.y, bound1.y)),', + ' max(bound0.z, bound1.z));', + ' bool active = (asuint(lo.x) & 0x7fffffffu) <= 0x7f800000u;', + ' hit = active && tmax >= max(0.0, tmin) && tmin < extent;', + ' return hit ? tmin : 3.402823466e+38;', + '}', # The five compare-exchange stages of Mesa radv_nir_rt_common.c: equal keys do not swap, # so misses (key +inf) sink to the end and unsorted hits keep their child order. 'void x2w_bvh_sort_pair(inout uint ia, inout uint ib, inout float ka, inout float kb) {', @@ -10364,6 +10383,43 @@ def read(fmt, data, offset): ' x2w_bvh_sort_pair(c1, c2, k1, k2);', ' return uint4(c0, c1, c2, c3);', '}', + 'uint4 x2w_bvh_intersect_box16(ByteAddressBuffer nodes, uint node, uint word0, uint word1,', + ' uint word2, uint word3, float extent, float3 origin,', + ' float3 inv_dir) {', + ' uint4 miss = uint4(X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS);', + ' if ((node & 7u) != 4u || !x2w_bvh_descriptor_ok(word0, word1, word2, word3)) return miss;', + ' uint offset = (node & 0xfffffff8u) << 3u;', + ' if ((offset >> 6u) + 1u > word2) return miss;', + ' inv_dir = clamp(inv_dir, -3.402823466e+38, 3.402823466e+38);', + ' bool h0, h1, h2, h3;', + ' float d0 = x2w_bvh_box16_slot(nodes, offset, 0u, extent, origin, inv_dir, h0);', + ' float d1 = x2w_bvh_box16_slot(nodes, offset, 1u, extent, origin, inv_dir, h1);', + ' float d2 = x2w_bvh_box16_slot(nodes, offset, 2u, extent, origin, inv_dir, h2);', + ' float d3 = x2w_bvh_box16_slot(nodes, offset, 3u, extent, origin, inv_dir, h3);', + ' bool sort_boxes = (word1 & 0x80000000u) != 0u;', + ' uint c0 = nodes.Load(offset);', + ' uint c1 = nodes.Load(offset + 4u);', + ' uint c2 = nodes.Load(offset + 8u);', + ' uint c3 = nodes.Load(offset + 12u);', + ' h0 = h0 && c0 != X2W_BVH_MISS;', + ' h1 = h1 && c1 != X2W_BVH_MISS;', + ' h2 = h2 && c2 != X2W_BVH_MISS;', + ' h3 = h3 && c3 != X2W_BVH_MISS;', + ' c0 = h0 ? c0 : X2W_BVH_MISS;', + ' c1 = h1 ? c1 : X2W_BVH_MISS;', + ' c2 = h2 ? c2 : X2W_BVH_MISS;', + ' c3 = h3 ? c3 : X2W_BVH_MISS;', + ' float k0 = h0 ? (sort_boxes ? d0 : 0.0) : 3.402823466e+38;', + ' float k1 = h1 ? (sort_boxes ? d1 : 0.0) : 3.402823466e+38;', + ' float k2 = h2 ? (sort_boxes ? d2 : 0.0) : 3.402823466e+38;', + ' float k3 = h3 ? (sort_boxes ? d3 : 0.0) : 3.402823466e+38;', + ' x2w_bvh_sort_pair(c0, c1, k0, k1);', + ' x2w_bvh_sort_pair(c2, c3, k2, k3);', + ' x2w_bvh_sort_pair(c0, c2, k0, k2);', + ' x2w_bvh_sort_pair(c1, c3, k1, k3);', + ' x2w_bvh_sort_pair(c1, c2, k1, k2);', + ' return uint4(c0, c1, c2, c3);', + '}', ) From c47f5987b5da21794e977d52b798c95b70a455f3 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Thu, 26 Nov 2026 21:39:29 +0000 Subject: [PATCH 04/44] tests: compile the binary16 BVH helper with DXC --- tests/startup_gfx2hlsl_bvh_check.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py index e72a2be0ac..d35c62ab70 100644 --- a/tests/startup_gfx2hlsl_bvh_check.py +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -386,6 +386,9 @@ def main(): pipe, hlsl, refusals = translate_program() assert not refusals, refusals compile_check(hlsl) + pipe, hlsl, refusals = translate_program(node=0x04) + assert not refusals, refusals + compile_check(hlsl) if failures: print("FAILED: %s" % ", ".join(failures)) return 1 From 1fd5475daedf183cf5a1fcecfb709f4414e5e40b Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Thu, 26 Nov 2026 21:41:07 +0000 Subject: [PATCH 05/44] tests: dispatch the binary16 BVH helper on WARP --- .../experiments/startup-gfx2hlsl-bvh-box32.md | 11 +++--- tests/startup_gfx2hlsl_bvh_check.py | 34 ++++++++++++++++--- 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md index 0f1bf29eec..3268e4e5ec 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-box32.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -58,11 +58,12 @@ prints `dxc compile: skip` and does not count that as a pass. python -B tests/startup_gfx2hlsl_bvh_check.py dispatch warp ``` -The dispatch mode compiles the same helper with a `RWByteAddressBuffer` in place of the bound -`ByteAddressBuffer`, writes the two synthetic nodes and five rays, and compares all twenty result words on a -Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.10068`). It also dispatches a mutant that leaves -missed child words in place; the case 2 word 0 must stop being `0xffffffff`. That control caught the first version -of this helper, which sorted the keys correctly but returned the original child pointer for a miss. +The dispatch mode compiles the helpers with a `RWByteAddressBuffer` in place of the bound +`ByteAddressBuffer`, writes the two FP32 nodes, one binary16 node and ten rays, and compares all forty result +words on a Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.10068`). All five FP32 and all five +binary16 cases pass on WARP. It also dispatches a mutant that leaves missed child words in place; the case 2 word 0 +must stop being `0xffffffff`. That control caught the first version of this helper, which sorted the keys +correctly but returned the original child pointer for a miss. This is a translator slice. It does not execute the native gfx1030 probe, does not bind the node buffer on a D3D12 device, and does not establish any title behavior. diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py index d35c62ab70..0894cae07e 100644 --- a/tests/startup_gfx2hlsl_bvh_check.py +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -112,6 +112,14 @@ def q(value): return quantized +HALF_BASE = 512 +HALF_NODES = half_nodes(NODES[0]) +HALF_RAYS = tuple( + (name, HALF_BASE, extent, origin, direction, reference(HALF_NODES, extent, origin, direction, True)) + for name, _offset, extent, origin, direction, _expected in RAYS +) + + def translate_program(*, node=0x05, sort_boxes=True, word0=0x00100000, word1=None, word2=0x0b, word3=RESOURCE_TYPE, loaded_descriptor=False, modifier="", opcode="image_bvh_intersect_ray", constant_node=True, stage_kind="cs"): @@ -312,6 +320,11 @@ def dispatch_hlsl(mutate_miss=False): lines.append(" data.Store(%du, %s);" % (base_offset + 16 + 24 * i + 12 + 4 * j, fbits(hi[j]))) for i in range(4): lines.append(" data.Store(%du, 0u);" % (base_offset + 112 + 4 * i)) + for i, (child, lo, hi) in enumerate(HALF_NODES): + lines.append(" data.Store(%du, 0x%08xu);" % (HALF_BASE + 4 * i, child)) + packed = struct.unpack("<3I", struct.pack("<6e", *lo, *hi)) + for j, word in enumerate(packed): + lines.append(" data.Store(%du, 0x%08xu);" % (HALF_BASE + 16 + 12 * i + 4 * j, word)) lines.append(" DeviceMemoryBarrierWithGroupSync();") for case, (_name, offset, extent, origin, direction, _expected) in enumerate(RAYS): inv = tuple(1.0 / c for c in direction) @@ -321,7 +334,16 @@ def dispatch_hlsl(mutate_miss=False): case, (offset >> 3) | 5, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), ffloat(origin[2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) for word in range(4): - lines.append(" data.Store(%du, r%d.%s);" % (512 + 16 * case + 4 * word, case, "xyzw"[word])) + lines.append(" data.Store(%du, r%d.%s);" % (576 + 16 * case + 4 * word, case, "xyzw"[word])) + for case, (_name, offset, extent, origin, direction, _expected) in enumerate(HALF_RAYS): + inv = tuple(1.0 / c for c in direction) + lines.append( + " uint4 h%d = x2w_bvh_intersect_box16(data, 0x%08xu, 0x00100000u, 0x80000000u, " + "0x00000040u, 0x80000000u, %s, float3(%s, %s, %s), float3(%s, %s, %s));" % ( + case, (offset >> 3) | 4, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), + ffloat(origin[2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) + for word in range(4): + lines.append(" data.Store(%du, h%d.%s);" % (672 + 16 * case + 4 * word, case, "xyzw"[word])) lines.append("}") return "\n".join(lines) + "\n" @@ -336,7 +358,7 @@ def run_dispatch(dxc, runner, adapter, directory, mutate=False): capture_output=True, text=True) if compiled.returncode or compiled.stderr: raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) - result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", "592", str(output)], + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", "768", str(output)], capture_output=True, text=True) print(result.stdout, end="") if result.returncode == 77: @@ -361,14 +383,18 @@ def check_dispatch(dxc, runner, adapter): print("dispatch: skip (adapter unavailable)") return 77 for case, (_name, _offset, _extent, _origin, _direction, expected) in enumerate(RAYS): - got = tuple(words[128 + 4 * case:132 + 4 * case]) + got = tuple(words[144 + 4 * case:148 + 4 * case]) check("dispatch case %d %s" % (case, _name), got == expected, "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in expected])) + for case, (_name, _offset, _extent, _origin, _direction, expected) in enumerate(HALF_RAYS): + got = tuple(words[168 + 4 * case:172 + 4 * case]) + check("dispatch box16 case %d %s" % (case, _name), got == expected, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in expected])) status, mutant = run_dispatch(dxc, runner, adapter, directory, mutate=True) if status == 77: print("dispatch control: skip (adapter unavailable)") return 77 - changed = mutant[128:132] + changed = mutant[144:148] check("dispatch miss-fill control decays case 2", tuple(changed) != (INVALID,) * 4, "got %s" % ["%08x" % w for w in changed]) if failures: From 94e90292e73a4eff8375d292e0453834e76a8092 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 08:53:51 +0000 Subject: [PATCH 06/44] startup: keep unsorted BVH hits in child order --- .../experiments/startup-gfx2hlsl-bvh-box32.md | 20 +++++++------ tests/startup_gfx2hlsl_bvh_check.py | 30 +++++++++++++++---- tools/startup/gfx2hlsl.py | 22 ++++++++++---- 3 files changed, 52 insertions(+), 20 deletions(-) diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md index 928459f57f..8e9521be92 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-box32.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -41,21 +41,23 @@ emits no helper call and no destination VGPR assignment. python -B tests/startup_gfx2hlsl_bvh_check.py ``` -The check compares the CPU box reference with the fixture in `tests/gfx1030_bvh_box/check.py` for five rays, -compares the emitted sort network with the same reference, checks the sort-bit negative control (word 0 changes -from `0x1d` to `0x25`), translates a synthetic constant-T# program and checks the four child results and the -manifest, and checks every refusal above. It also compiles the translated compute shader with DXC when one is -available; without DXC it prints `dxc compile: skip` and does not count that as a pass. +The check compares the CPU box reference with the fixture in `tests/gfx1030_bvh_box/check.py` for six rays, +compares the emitted helper with the same reference, checks the sort-bit negative control (word 0 changes from +`0x1d` to `0x25`), checks the three-hit sort-disabled case whose equal keys must stay in child order +(`0x25, 0x2d, 0x35, 0xffffffff`), translates a synthetic constant-T# program and checks the four child results +and the manifest, and checks every refusal above. It also compiles the translated compute shader with DXC when +one is available; without DXC it prints `dxc compile: skip` and does not count that as a pass. ```text python -B tests/startup_gfx2hlsl_bvh_check.py dispatch warp ``` The dispatch mode compiles the same helper with a `RWByteAddressBuffer` in place of the bound -`ByteAddressBuffer`, writes the two synthetic nodes and five rays, and compares all twenty result words on a -Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.10068`). It also dispatches a mutant that leaves -missed child words in place; the case 2 word 0 must stop being `0xffffffff`. That control caught the first version -of this helper, which sorted the keys correctly but returned the original child pointer for a miss. +`ByteAddressBuffer`, writes the three synthetic nodes and six rays, and compares all twenty-four result words on +a Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.10068`). It also dispatches a mutant that +leaves missed child words in place; the all-miss case 2 word 0 at words 136..139 must stop being +`0xffffffff`. That control caught the first version of this helper, which sorted the keys correctly but +returned the original child pointer for a miss. This is a translator slice. It does not execute the native gfx1030 probe, does not bind the node buffer on a D3D12 device, and does not establish any title behavior. diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py index cc40ed6667..35cecf48d9 100644 --- a/tests/startup_gfx2hlsl_bvh_check.py +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -39,6 +39,7 @@ def box(child, depth, x=-8): NODES = { 0: (box(0x25, 4), box(0x1d, 1), box(0x2d, 2, x=32), box(INVALID, 3)), 256: (box(0x45, 7), box(0x3d, 5), box(0x35, 3), box(0x0d, 1)), + 384: (box(0x25, 4), box(INVALID, 1), box(0x2d, 2), box(0x35, 3)), } ORIGIN = (0.5, -0.5, -1.0) FORWARD = (0.25, -0.125, 0.5) @@ -49,6 +50,9 @@ def box(child, depth, x=-8): ("all_four", 256, 19.0, ORIGIN, FORWARD, (0x0d, 0x35, 0x3d, 0x45)), ("reverse", 0, 21.0, (0.0, 0.0, 10.0), (0.25, -0.125, -0.5), (0x25, 0x1d, INVALID, INVALID)), ) +UNSORTED_RAYS = ( + ("unsorted_three_hits", 384, 19.0, ORIGIN, FORWARD, (0x25, 0x2d, 0x35, INVALID)), +) failures = [] @@ -96,6 +100,9 @@ def model(nodes, extent, origin, direction, sort_boxes): items.append([child, tmin if sort_boxes else 0.0]) else: items.append([INVALID, FLT_MAX]) + if not sort_boxes: + ordered = [child for child, _key in items if child != INVALID] + return tuple(ordered) + (INVALID,) * (4 - len(ordered)) for a, b in ((0, 1), (2, 3), (0, 2), (1, 3), (1, 2)): if items[b][1] < items[a][1]: items[a], items[b] = items[b], items[a] @@ -169,6 +176,13 @@ def controls(): check("model without the sort bit matches the unsorted reference", model(NODES[0], 19.0, ORIGIN, FORWARD, False) == unsorted, str((model(NODES[0], 19.0, ORIGIN, FORWARD, False), unsorted))) + for name, offset, extent, origin, direction, expected in UNSORTED_RAYS: + actual = reference(NODES[offset], extent, origin, direction, False) + check("CPU reference keeps child order with the sort bit clear (%s)" % name, actual == expected, + str((actual, expected))) + actual = model(NODES[offset], extent, origin, direction, False) + check("helper keeps child order with the sort bit clear (%s)" % name, actual == expected, + str((actual, expected))) check("all-miss result is four 0xffffffff words", reference(NODES[0], 2.0, ORIGIN, FORWARD, True) == (INVALID,) * 4, "") @@ -290,12 +304,13 @@ def dispatch_hlsl(mutate_miss=False): for i in range(4): lines.append(" data.Store(%du, 0u);" % (base_offset + 112 + 4 * i)) lines.append(" DeviceMemoryBarrierWithGroupSync();") - for case, (_name, offset, extent, origin, direction, _expected) in enumerate(RAYS): + for case, (_name, offset, extent, origin, direction, _expected) in enumerate(RAYS + UNSORTED_RAYS): inv = tuple(1.0 / c for c in direction) + sort_word = "0x80000000u" if case < len(RAYS) else "0x00000000u" lines.append( - " uint4 r%d = x2w_bvh_intersect_box32(data, 0x%08xu, 0x00100000u, 0x80000000u, " + " uint4 r%d = x2w_bvh_intersect_box32(data, 0x%08xu, 0x00100000u, %s, " "0x0000000bu, 0x80000000u, %s, float3(%s, %s, %s), float3(%s, %s, %s));" % ( - case, (offset >> 3) | 5, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), + case, (offset >> 3) | 5, sort_word, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), ffloat(origin[2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) for word in range(4): lines.append(" data.Store(%du, r%d.%s);" % (512 + 16 * case + 4 * word, case, "xyzw"[word])) @@ -313,7 +328,7 @@ def run_dispatch(dxc, runner, adapter, directory, mutate=False): capture_output=True, text=True) if compiled.returncode or compiled.stderr: raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) - result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", "592", str(output)], + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", "608", str(output)], capture_output=True, text=True) print(result.stdout, end="") if result.returncode == 77: @@ -341,11 +356,16 @@ def check_dispatch(dxc, runner, adapter): got = tuple(words[128 + 4 * case:132 + 4 * case]) check("dispatch case %d %s" % (case, _name), got == expected, "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in expected])) + for extra, (_name, _offset, _extent, _origin, _direction, expected) in enumerate(UNSORTED_RAYS): + case = len(RAYS) + extra + got = tuple(words[128 + 4 * case:132 + 4 * case]) + check("dispatch case %d %s" % (case, _name), got == expected, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in expected])) status, mutant = run_dispatch(dxc, runner, adapter, directory, mutate=True) if status == 77: print("dispatch control: skip (adapter unavailable)") return 77 - changed = mutant[128:132] + changed = mutant[136:140] check("dispatch miss-fill control decays case 2", tuple(changed) != (INVALID,) * 4, "got %s" % ["%08x" % w for w in changed]) if failures: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index e168f447ff..6912c58f1a 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -10785,12 +10785,22 @@ def read(fmt, data, offset): ' c1 = h1 ? c1 : X2W_BVH_MISS;', ' c2 = h2 ? c2 : X2W_BVH_MISS;', ' c3 = h3 ? c3 : X2W_BVH_MISS;', - # A disabled sort uses one key for every hit: the network then only compacts misses, - # while an enabled sort orders the hits by entry distance. - ' float k0 = h0 ? (sort_boxes ? d0 : 0.0) : 3.402823466e+38;', - ' float k1 = h1 ? (sort_boxes ? d1 : 0.0) : 3.402823466e+38;', - ' float k2 = h2 ? (sort_boxes ? d2 : 0.0) : 3.402823466e+38;', - ' float k3 = h3 ? (sort_boxes ? d3 : 0.0) : 3.402823466e+38;', + # Sorting disabled keeps the children in their original order. Do not reuse the sort network: + # its nonadjacent compare-exchange stages move a later hit into an earlier position while + # compacting the miss between them, which reorders equal keys. + ' if (!sort_boxes) {', + ' uint4 ordered = miss;', + ' uint n = 0u;', + ' if (h0) ordered[n++] = c0;', + ' if (h1) ordered[n++] = c1;', + ' if (h2) ordered[n++] = c2;', + ' if (h3) ordered[n++] = c3;', + ' return ordered;', + ' }', + ' float k0 = h0 ? d0 : 3.402823466e+38;', + ' float k1 = h1 ? d1 : 3.402823466e+38;', + ' float k2 = h2 ? d2 : 3.402823466e+38;', + ' float k3 = h3 ? d3 : 3.402823466e+38;', ' x2w_bvh_sort_pair(c0, c1, k0, k1);', ' x2w_bvh_sort_pair(c2, c3, k2, k3);', ' x2w_bvh_sort_pair(c0, c2, k0, k2);', From b7117d4646a94ad6e4a55d8b3f1357bdb5398b27 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 14:05:36 +0000 Subject: [PATCH 07/44] docs: correct the binary16 node count in the BVH receipt --- docs/experiments/startup-gfx2hlsl-bvh-box32.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md index 29581cb27d..e598f60279 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-box32.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -71,7 +71,7 @@ python -B tests/startup_gfx2hlsl_bvh_check.py dispatch w ``` The dispatch mode compiles both helpers with a `RWByteAddressBuffer` in place of the bound -`ByteAddressBuffer`, writes four FP32 nodes, three binary16 nodes and twenty-one rays, and compares the +`ByteAddressBuffer`, writes four FP32 nodes, four binary16 nodes and twenty-one rays, and compares the four result DWORDs for every case (1232-byte readback). All eight sorted FP32 cases, three unsorted FP32 cases, eight sorted binary16 cases (including the rounded bound and both encoded bases) and two unsorted binary16 cases pass on a Microsoft Basic Render Driver (`1414:008c`, driver `10.0.26100.10068`) and on an From 5640a90392adf25e2ae3ef29e55245596d844073 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 14:51:43 +0000 Subject: [PATCH 08/44] startup: lower triangle nodes in image_bvh_intersect_ray Accept the 64-byte triangle node forms (kinds 0..3), decode their four ID maps and base vertex triples, and emit a watertight ray/triangle helper for return mode 1. The helper returns {t, det, v, w} and keeps the 48-bit descriptor rules. 119 CPU witnesses pass bit-for-bit on WARP and the RX 9060 XT in dev and release, with four negative mutations; the existing box tests remain green. --- .../startup-gfx2hlsl-bvh-triangle.md | 75 +++++ .../cmake/startup_gfx2hlsl_bvh_triangle.cmake | 15 + tests/startup_gfx2hlsl_bvh_check.py | 11 +- tests/startup_gfx2hlsl_bvh_triangle_check.py | 311 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 117 ++++++- 5 files changed, 507 insertions(+), 22 deletions(-) create mode 100644 docs/experiments/startup-gfx2hlsl-bvh-triangle.md create mode 100644 tests/cmake/startup_gfx2hlsl_bvh_triangle.cmake create mode 100644 tests/startup_gfx2hlsl_bvh_triangle_check.py diff --git a/docs/experiments/startup-gfx2hlsl-bvh-triangle.md b/docs/experiments/startup-gfx2hlsl-bvh-triangle.md new file mode 100644 index 0000000000..c5b8691f6e --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-bvh-triangle.md @@ -0,0 +1,75 @@ +# `image_bvh_intersect_ray` triangle nodes + +`tools/startup/gfx2hlsl.py` now lowers the 64-byte triangle node forms (kinds 0..3) of the 32-bit +`image_bvh_intersect_ray` (RDNA 2 MIMG opcode 230), in addition to the FP32 and binary16 box nodes. + +## Node and test + +A triangle node is 64 bytes: five `float3` vertices at bytes 0..59 and one ID dword at byte 60. The +kind selects one of the four 8-bit maps in the ID dword. Each map holds `i` in two bits and `j` in +two bits; the third index is `(3 - i - j) & 3`. The kind also selects the base vertex triple, which +is the table in Mesa 25.1.0 RADV's `radv_bvh_triangle_node` (MIT): + +```text +kind 0: 0 1 2 +kind 1: 1 3 2 +kind 2: 2 3 4 +kind 3: 2 4 0 +``` + +The test is the watertight ray/triangle formulation from Woop, Benthin and Wald, as RADV uses it. +The helper projects the vertices onto the dominant ray axis, shears them, computes the three +barycentric numerators `u`, `v` and `w`, the determinant `u + (v + w)` and +`t = u*az + v*bz + w*cz` in binary32. A hit requires all three barycentrics to share a sign and +`t` to have the matching sign. The instruction does not test `ray_extent` for triangles. + +## Return and descriptor + +Triangle return mode 1 (bit 120 of the BVH T#, bit 24 of descriptor DWORD 3) returns the four words +`{t, determinant, v, w}` as float bit patterns. A miss is `{+inf, 1.0, 0, 0}`. Return mode 0 and +every other reserved word-3 bit are refused by name before any HLSL is emitted. + +The accepted slice uses: + +- compute stage only; +- `image_bvh_intersect_ray v[4], v[11], s[4]` with the packed address form; +- a constant inline T# built by four SGPR constants, type 8, nonzero encoded base, box growing zero, + size at least one 64-byte unit and below 4 GiB; +- a constant node pointer whose low three bits are 0..3 and whose address is inside the descriptor + size and the 48-bit absolute address space; +- either value of the sort bit; it is ignored for triangles. + +The manifest still names the allocation with `srv bvh base 0x size 0x`, using the +decoded byte address for `base`. The host binding of that line remains outside this change. + +## Refused by name + +Return mode 0, every node kind other than 0..3, `image_bvh64_intersect_ray`, A16, non-sequential +addresses, a pixel or vertex stage, a node pointer that is not a straight-line constant, a T# loaded +at run time, a type other than 8, nonzero box growing, an absolute (zero) base, a size that does not +cover the node, size bits above 4 GiB, a 48-bit node wrap, and every reserved T# field. The checks +assert that a refusal emits no helper call and no destination VGPR assignment. + +## Evidence + +```sh +python3 -B tests/startup_gfx2hlsl_bvh_triangle_check.py +python3 -B tests/startup_gfx2hlsl_bvh_triangle_check.py dispatch warp +``` + +The check reuses the 119 triangle witnesses in `tests/gfx1030_bvh_box/check.py` and the independent +model in `tests/gfx1030_bvh_box/bvh_model.py`. It covers all four kinds, every ID map byte, edge and +vertex hits, outside and behind rays, zero direction and negative zero, `t = 0`, `extent = 0`, +1024x scaling in both directions, degenerate and malformed nodes, and the box kinds 6 and 7. + +The dispatch writes 71 unique triangle images at 64-byte offsets, runs the emitted helper for all +119 witnesses, and compares all 476 result words. It passes on WARP (`1414:008c`, driver +`10.0.26100.10068`) and on an AMD Radeon RX 9060 XT (`1002:7590`, driver `32.0.32029.2010`), in +both the dev and release presets, with `dxc -Gis` matching the runtime's strict-IEEE compile. Four +mutants change the determinant sign, the ID shift, the `u` term and the miss words; each must change +at least one witness. The existing box32/box16 tests still pass 6/6 in both presets. + +This is a translator slice. It does not bind the node buffer on a D3D12 device, does not execute the +native gfx1030 probe, and does not establish title behavior. The runtime manifest loader does not yet +consume the `bvhbase` line, so a real dispatch is refused rather than bound at a wrong address. + diff --git a/tests/cmake/startup_gfx2hlsl_bvh_triangle.cmake b/tests/cmake/startup_gfx2hlsl_bvh_triangle.cmake new file mode 100644 index 0000000000..db06bf7e60 --- /dev/null +++ b/tests/cmake/startup_gfx2hlsl_bvh_triangle.cmake @@ -0,0 +1,15 @@ +# gfx2hlsl image_bvh_intersect_ray triangle-node slice: translator controls, a DXC compile when +# one is available, and a WARP/hardware dispatch when offscreen_check is built. +if(EXISTS "${INTAKE_PYTHON}") + add_test(NAME startup_gfx2hlsl_bvh_triangle COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bvh_triangle_check.py") +endif() +if(EXISTS "${INTAKE_PYTHON}" AND TARGET offscreen_check) + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_bvh_triangle_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_bvh_triangle_check.py" dispatch "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_gfx2hlsl_bvh_triangle_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() + diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py index 5e7cfbdd40..36b9fa1842 100644 --- a/tests/startup_gfx2hlsl_bvh_check.py +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -3,8 +3,8 @@ The instruction is RDNA 2 MIMG opcode 230. This check covers the translator path and the box model only: a constant inline BVH T#[12:15], an 11-dword packed address, a constant node base whose low three bits are 4 (binary16) or 5 (FP32), and the four child results. -Triangle nodes, the 64-bit form, A16, NSA and every dynamic descriptor or node base are -refused by name before any HLSL is emitted. The independent CPU box reference is +The triangle kinds have a dedicated check. The 64-bit form, A16, NSA and every dynamic +descriptor or node base are refused by name before any HLSL is emitted. The independent CPU box reference is tests/gfx1030_bvh_box/bvh_model.py; the Windows dispatch exercises both emitted helpers. """ import math @@ -407,7 +407,6 @@ def controls(): # Every refusal must happen before a helper call or a result VGPR is emitted. cases = [ - ("triangle node", dict(node=0x00), "triangle node (kind 0)"), ("unknown node kind", dict(node=0x06), "node kind 6"), ("unaligned node", dict(node=0x0d), "not an aligned 128-byte node"), ("non-constant node", dict(constant_node=False), "non-constant node base"), @@ -422,7 +421,7 @@ def controls(): ("node outside size", dict(node=0x25, word2=3), "outside descriptor size"), ("box16 node outside size", dict(node=0x54, word2=10), "outside descriptor size"), ("absolute base", dict(word0=0, word1=0), "absolute node base"), - ("size high bits", dict(word3=RESOURCE_TYPE | 0x100), "size above 4 GiB"), + ("size high bits", dict(word3=RESOURCE_TYPE | 0x100), "does not match node kind 5"), ] for label, kwargs, reason in cases: if label == "NSA address": @@ -470,7 +469,7 @@ def compile_check(hlsl): with tempfile.TemporaryDirectory(dir=ROOT / "out" if (ROOT / "out").is_dir() else None) as temporary: source = Path(temporary) / "bvh_box.hlsl" source.write_text(hlsl, encoding="ascii") - result = subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", str(source.with_suffix(".cso")), str(source)], + result = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(source.with_suffix(".cso")), str(source)], capture_output=True, text=True) if result.returncode or result.stderr: check("dxc compiles the translated helper", False, result.stderr or "exit %d" % result.returncode) @@ -550,7 +549,7 @@ def run_dispatch(dxc, runner, adapter, directory, mutation=None): cso = directory / (name + ".cso") output = directory / (name + ".bin") source.write_text(dispatch_hlsl(mutation), encoding="ascii") - compiled = subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + compiled = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], capture_output=True, text=True) if compiled.returncode or compiled.stderr: raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) diff --git a/tests/startup_gfx2hlsl_bvh_triangle_check.py b/tests/startup_gfx2hlsl_bvh_triangle_check.py new file mode 100644 index 0000000000..a2c749f9f4 --- /dev/null +++ b/tests/startup_gfx2hlsl_bvh_triangle_check.py @@ -0,0 +1,311 @@ +"""image_bvh_intersect_ray: the triangle-node (kinds 0..3) translation slice. + +The instruction is RDNA 2 MIMG opcode 230. A triangle node is 64 bytes: five float3 vertices +and one ID dword. This check covers the translator, the watertight ray/triangle test and the +four-word return `{t, determinant, v, w}` for triangle return mode 1. The independent model is +tests/gfx1030_bvh_box/bvh_model.py; the dispatch runs the emitted helper on WARP or hardware. +""" +import math +import os +from pathlib import Path +import shutil +import struct +import subprocess +import sys +import tempfile + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT / "tools" / "startup")) +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE / "gfx1030_bvh_box")) +import gfx2hlsl as G # noqa: E402 +import startup_gfx2hlsl_bvh_check as BOX # noqa: E402 +import check as F # noqa: E402 +from gfx1030_bvh_box import bvh_model as B # noqa: E402 + +SORT_ENABLE = 1 << 31 +RESOURCE_TYPE = 1 << 31 +TRIANGLE_MODE = 1 << 24 +TRIANGLES = tuple(case for case in F.WITNESSES if case.name.startswith("tri/") and not case.wide) + +failures = [] + + +def check(label, ok, detail=""): + print("%s: %s" % (label, "ok" if ok else "MISMATCH"), flush=True) + if not ok: + failures.append(label) + if detail: + print(" " + detail) + + +def translate_triangle(node, **kwargs): + kwargs.setdefault("word3", RESOURCE_TYPE | TRIANGLE_MODE) + return BOX.translate_program(node=node, **kwargs) + + +def controls(): + bad = None + for case in TRIANGLES: + origin, direction, inverse, extent = case.ray + actual = tuple(B.intersect( + bytearray(case.image), B.descriptor(0, sort=True), case.pointer, + origin=origin, direction=direction, inverse=inverse, extent=extent)) + if actual != case.expected: + bad = (case.name, actual, case.expected) + break + check("independent model matches every triangle fixture", bad is None, str(bad)) + + for kind in range(4): + pipe, hlsl, refusals = translate_triangle(kind) + check("triangle kind %d translates" % kind, pipe is not None and not refusals, str(refusals)) + if pipe is None: + continue + manifest = pipe.manifest() + check("triangle kind %d manifest names the node allocation" % kind, + "srv 0 bvh base 0x100000 size 0xb" in manifest, manifest) + check("triangle kind %d HLSL contains the helper" % kind, + "uint4 x2w_bvh_intersect_triangle" in hlsl and "x2w_bvh_triangle_vertex" in hlsl + and "x2w_bvh_shear" in hlsl, "") + call_line = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_triangle(r0" in line), "") + check("triangle kind %d call carries all four descriptor DWORDs" % kind, + "0x00001000u, 0x80000000u, 0x0000000bu, 0x81000000u" in call_line, call_line) + check("triangle kind %d call carries the node and four results" % kind, + "0x0000000%du" % kind in call_line + and all("v%d = bt" % reg in hlsl for reg in range(32, 36)), call_line) + + pipe, hlsl, refusals = translate_triangle(0x00, sort_boxes=False) + check("sort-disabled triangle translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + call = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_triangle(r0" in line), "") + check("sort-disabled triangle call keeps the zero sort word", + "0x00001000u, 0x00000000u, 0x0000000bu, 0x81000000u" in call, call) + + helpers = "\n".join(G.BVH_HELPERS) + check("translated triangle shader embeds the dispatch-tested helpers", + hlsl is not None and helpers in hlsl, "") + + cases = [ + ("triangle return mode 0", dict(node=0x00, word3=RESOURCE_TYPE), "does not match node kind 0"), + ("box return mode 1", dict(node=0x05, word3=RESOURCE_TYPE | TRIANGLE_MODE), "does not match node kind 5"), + ("unknown node kind", dict(node=0x06), "node kind 6"), + ("size zero", dict(node=0x00, word2=0), "does not cover the node"), + ("node outside size", dict(node=0x20, word2=4), "outside descriptor size"), + ("absolute base", dict(node=0x00, word0=0, word1=0), "absolute node base"), + ("loaded descriptor", dict(node=0x00, loaded_descriptor=True), "loaded at run time"), + ("descriptor type", dict(node=0x00, word3=0x60000000), "descriptor type 6 is not 8"), + ("box growing", dict(node=0x00, word1=SORT_ENABLE | (2 << 23)), "box growing amount 2"), + ("reserved word 1", dict(node=0x00, word1=SORT_ENABLE | 0x100), "reserved word 1"), + ("8-bit return mode extra bit", dict(node=0x00, word3=RESOURCE_TYPE | TRIANGLE_MODE | 0x100), + "does not match node kind 0"), + ("64-bit form", dict(node=0x00, opcode="image_bvh64_intersect_ray"), "image_bvh64_intersect_ray"), + ("A16", dict(node=0x00, modifier="a16"), "modifier a16"), + ("unaligned box32 node", dict(node=0x0d), "not an aligned 128-byte node"), + ] + for label, kwargs, reason in cases: + if label == "NSA address": + pipe, hlsl, refusals = None, None, [] + try: + G.Stage.op_image_bvh_intersect_ray( + type("P", (), {"kind": "cs", "const_u32": lambda self, tok: 0})(), + ("v[32:35]", "[v0, v2, v4, v6, v8, v10, v12, v14, v16, v18, v20]", "s[12:15]"), []) + except G.Unsupported as error: + refusals = [str(error)] + else: + pipe, hlsl, refusals = translate_triangle(**kwargs) + ok = len(refusals) == 1 and reason in refusals[0] + check("refuses %s" % label, ok, str(refusals)) + if hlsl is not None: + check(" no partial output for %s" % label, + "uint4 bt" not in hlsl and "x2w_bvh_intersect_triangle(r" not in hlsl, "") + + words = (0xffffffff, SORT_ENABLE | 0xff, 0x0b, RESOURCE_TYPE | TRIANGLE_MODE) + pipe, boundary_hlsl, refusals = translate_triangle(0x10, word0=words[0], word1=words[1]) + check("triangle node ending exactly at the 48-bit boundary translates", + pipe is not None and not refusals, str(refusals)) + pipe, wrap_hlsl, refusals = translate_triangle(0x20, word0=words[0], word1=words[1]) + check("refuses a triangle 48-bit wrap before resource binding", + refusals == ["image_bvh_intersect_ray node address wraps the 48-bit address space"] + and " bvh base " not in pipe.manifest() + and "x2w_bvh_intersect_triangle" not in wrap_hlsl and "uint4 bt" not in wrap_hlsl, str(refusals)) + + pipe, hlsl, refusals = translate_triangle(0x00, stage_kind="ps") + check("refuses a triangle pixel stage", len(refusals) == 1 and "outside a compute stage" in refusals[0], str(refusals)) + + +def find_dxc(): + named = os.environ.get("X2W_DXC") + if named and Path(named).is_file(): + return str(Path(named)) + found = shutil.which("dxc") + if found: + return found + kits = os.environ.get("ProgramFiles(x86)", "") + if kits: + candidates = sorted((Path(kits) / "Windows Kits" / "10" / "bin").glob("*/x64/dxc.exe"), reverse=True) + if candidates: + return str(candidates[0]) + return None + + +def compile_check(hlsl): + dxc = find_dxc() + if dxc is None: + print("dxc compile: skip (no dxc on this host)") + return None + with tempfile.TemporaryDirectory(dir=ROOT / "out" if (ROOT / "out").is_dir() else None) as temporary: + source = Path(temporary) / "bvh_triangle.hlsl" + source.write_text(hlsl, encoding="ascii") + result = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(source.with_suffix(".cso")), str(source)], + capture_output=True, text=True) + if result.returncode or result.stderr: + check("dxc compiles the translated triangle helper", False, result.stderr or "exit %d" % result.returncode) + return False + print("dxc compile: ok (%s)" % dxc) + return True + + +def ffloat(value): + return "asfloat(0x%08xu)" % struct.unpack(" 0.0 && t >= 0.0) || (det < 0.0 && t <= 0.0);", + "bool ahead = (det > 0.0 && t >= 0.0) || (det > 0.0 && t <= 0.0);"), + "id_shift": ( + "uint id_byte = (id >> (8u * kind)) & 0xffu;", + "uint id_byte = id & 0xffu;"), + "u_sign": ( + "float u = sc.x * sb.y - sc.y * sb.x;", + "float u = sc.x * sb.y + sc.y * sb.x;"), + "miss_words": ( + "uint4 miss = uint4(0x7f800000u, 0x3f800000u, 0u, 0u);", + "uint4 miss = uint4(0u, 0u, 0u, 0u);"), +} + + +def dispatch_hlsl(mutation=None): + helpers = "\n".join(G.BVH_HELPERS).replace("ByteAddressBuffer", "RWByteAddressBuffer") + if mutation: + old, new = MUTATIONS[mutation] + assert helpers.count(old) == 1, (mutation, old) + helpers = helpers.replace(old, new) + images, offsets, result_offset, _buffer_size = triangle_layout() + lines = [helpers, "RWByteAddressBuffer data : register(u0);", "[numthreads(1, 1, 1)]", "void main() {"] + for image in images: + base = offsets[image] + for i in range(16): + lines.append(" data.Store(%du, 0x%08xu);" % (base + 4 * i, struct.unpack_from("> 3) | witness.pointer + lines.append( + " uint4 r%d = x2w_bvh_intersect_triangle(data, 0x%08xu, 0x1000u, 0x80000000u, " + "0x400u, 0x81000000u, float3(%s, %s, %s), float3(%s, %s, %s), float3(%s, %s, %s));" % ( + case, pointer, ffloat(origin[0]), ffloat(origin[1]), ffloat(origin[2]), + ffloat(direction[0]), ffloat(direction[1]), ffloat(direction[2]), + ffloat(inverse[0]), ffloat(inverse[1]), ffloat(inverse[2]))) + for word in range(4): + lines.append(" data.Store(%du, r%d.%s);" % (result_offset + 16 * case + 4 * word, case, "xyzw"[word])) + lines.append("}") + return "\n".join(lines) + "\n" + + +def run_dispatch(dxc, runner, adapter, directory, mutation=None): + _images, _offsets, _result_offset, buffer_size = triangle_layout() + name = "bvh_triangle_" + mutation if mutation else "bvh_triangle" + source = directory / (name + ".hlsl") + cso = directory / (name + ".cso") + output = directory / (name + ".bin") + source.write_text(dispatch_hlsl(mutation), encoding="ascii") + compiled = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + capture_output=True, text=True) + if compiled.returncode or compiled.stderr: + raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", str(buffer_size), str(output)], + capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return 77, None + if result.returncode or result.stderr: + raise AssertionError(result.stderr or "offscreen_check exited with %d" % result.returncode) + data = output.read_bytes() + assert len(data) == buffer_size, (len(data), buffer_size) + return 0, struct.unpack("<%dI" % (len(data) // 4), data) + + +def check_dispatch(dxc, runner, adapter): + controls() + if failures: + return 1 + if not dxc or not runner: + print("dispatch: skip (no dxc or offscreen_check)") + return 77 + out = ROOT / "out" + out.mkdir(exist_ok=True) + _images, _offsets, result_offset, _buffer_size = triangle_layout() + result_word = result_offset // 4 + with tempfile.TemporaryDirectory(dir=out) as temporary: + directory = Path(temporary) + status, words = run_dispatch(dxc, runner, adapter, directory) + if status == 77: + print("dispatch: skip (adapter unavailable)") + return 77 + for case, witness in enumerate(TRIANGLES): + start = result_word + 4 * case + got = tuple(words[start:start + 4]) + check("dispatch triangle %d %s" % (case, witness.name), got == witness.expected, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in witness.expected])) + for mutation in MUTATIONS: + status, mutant = run_dispatch(dxc, runner, adapter, directory, mutation=mutation) + if status == 77: + print("dispatch control: skip (adapter unavailable)") + return 77 + changed = sum(tuple(mutant[result_word + 4 * case:result_word + 4 * case + 4]) != witness.expected + for case, witness in enumerate(TRIANGLES)) + check("dispatch %s control changes a triangle result" % mutation, changed > 0, str(changed)) + if failures: + print("FAILED: %s" % ", ".join(failures)) + return 1 + print("dispatch: all ok on %s" % adapter) + return 0 + + +def main(): + if len(sys.argv) == 5 and sys.argv[1] == "dispatch": + return check_dispatch(sys.argv[2], sys.argv[3], sys.argv[4]) + if len(sys.argv) != 1: + sys.exit(__doc__) + controls() + pipe, hlsl, refusals = translate_triangle(0x00) + assert not refusals, refusals + compile_check(hlsl) + if failures: + print("FAILED: %s" % ", ".join(failures)) + return 1 + print("startup gfx2hlsl bvh triangle: all ok") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) + diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index a4dc8dc125..2473664beb 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -8051,18 +8051,21 @@ def bvh_descriptor(self, tok): return (('bvhbase', base, values[2]), None), words, values def op_image_bvh_intersect_ray(self, ops, mods): - """Ray/box intersection for the 128-byte FP32 (kind 5) and 64-byte binary16 (kind 4) box nodes. + """Ray/box/triangle intersection for the 64-byte triangle (kinds 0..3), 64-byte binary16 + (kind 4) and 128-byte FP32 (kind 5) nodes. RDNA 2 ISA section 8.2.10 and Table 48: VDATA is four result dwords, VADDR is 11 dwords (node pointer, extent, origin xyz, direction xyz, inverse direction xyz) and SRSRC is the four-word BVH T# of Table 49. This first slice accepts only a straight-line compute program - with a constant node base, a constant inline T# and a node whose kind bits are 4 or 5. + with a constant node base, a constant inline T# and a node whose kind bits are 0..5. The descriptor base encodes address bits 47:8 in 256-byte units and binds a ByteAddressBuffer at that byte address; the node pointer is an offset in 8-byte units from that base. The emitted helper performs the four slab tests, clips against extent, replaces misses with 0xffffffff in their original slots, and sorts by entry distance only when the - descriptor's box-sorting enable bit is set. Triangle nodes, the 64-bit form, A16, - non-sequential addresses and every other node kind are refused by name. + descriptor's box-sorting enable bit is set. Triangle nodes use the watertight test and + return {t, determinant, v, w} for triangle return mode 1; the instruction does not test + ray_extent for them. The 64-bit form, A16, non-sequential addresses and every other node + kind are refused by name. """ name = 'image_bvh_intersect_ray' if self.kind != 'cs': @@ -8087,14 +8090,14 @@ def op_image_bvh_intersect_ray(self, ops, mods): if node is None: raise Unsupported('%s non-constant node base %s' % (name, cs[0])) kind = node & 7 - if 0 <= kind <= 3: - raise Unsupported('%s triangle node (kind %d) is not lowered' % (name, kind)) - if kind not in (4, 5): + if kind not in (0, 1, 2, 3, 4, 5): raise Unsupported('%s node kind %d is not lowered' % (name, kind)) + triangle = kind <= 3 half_box = kind == 4 - node_bytes = 64 if half_box else 128 + node_bytes = 64 if triangle or half_box else 128 node_offset = (node & 0xfffffff8) << 3 - if node_offset > (0xffffffc0 if half_box else 0xffffff80) or node_offset & (0x3f if half_box else 0x7f): + if node_offset > (0xffffffc0 if node_bytes == 64 else 0xffffff80) or \ + node_offset & (0x3f if node_bytes == 64 else 0x7f): raise Unsupported('%s node base %#x is not an aligned %u-byte node' % (name, node_offset, node_bytes)) key, words, vals = self.bvh_descriptor(ops[2]) if vals[1] is not None: @@ -8105,8 +8108,9 @@ def op_image_bvh_intersect_ray(self, ops, mods): if vals[3] is not None: if (vals[3] >> 28) & 0xf != 8: raise Unsupported('%s descriptor type %d is not 8' % (name, (vals[3] >> 28) & 0xf)) - if vals[3] & 0x0fffffff: - raise Unsupported('%s descriptor size above 4 GiB or reserved word 3 %#x' % (name, vals[3])) + expected_mode = 0x01000000 if triangle else 0 + if (vals[3] & 0x0fffffff) != expected_mode: + raise Unsupported('%s descriptor word 3 %#x does not match node kind %d' % (name, vals[3], kind)) base = key[0][1] if base == 0: raise Unsupported('%s absolute node base is not lowered' % name) @@ -8119,14 +8123,21 @@ def op_image_bvh_intersect_ray(self, ops, mods): raise Unsupported('%s node address wraps the 48-bit address space' % name) extent = self.f(cs[1]) origin = [self.f(cs[2 + i]) for i in range(3)] - [self.f(cs[5 + i]) for i in range(3)] # the instruction consumes ray_dir; the helper uses inv_dir + direction = [self.f(cs[5 + i]) for i in range(3)] inv_dir = [self.f(cs[8 + i]) for i in range(3)] res = self.pipe.resource(key, 'bvh') self.pipe.uses_bvh = True - call = '%s(%s, 0x%08xu, %s, %s, %s, %s, %s, float3(%s, %s, %s), float3(%s, %s, %s))' % ( - 'x2w_bvh_intersect_box16' if half_box else 'x2w_bvh_intersect_box32', - res, node, words[0], words[1], words[2], words[3], extent, - origin[0], origin[1], origin[2], inv_dir[0], inv_dir[1], inv_dir[2]) + if triangle: + call = ('x2w_bvh_intersect_triangle(%s, 0x%08xu, %s, %s, %s, %s, ' + 'float3(%s, %s, %s), float3(%s, %s, %s), float3(%s, %s, %s))') % ( + res, node, words[0], words[1], words[2], words[3], + origin[0], origin[1], origin[2], direction[0], direction[1], direction[2], + inv_dir[0], inv_dir[1], inv_dir[2]) + else: + call = '%s(%s, 0x%08xu, %s, %s, %s, %s, %s, float3(%s, %s, %s), float3(%s, %s, %s))' % ( + 'x2w_bvh_intersect_box16' if half_box else 'x2w_bvh_intersect_box32', + res, node, words[0], words[1], words[2], words[3], extent, + origin[0], origin[1], origin[2], inv_dir[0], inv_dir[1], inv_dir[2]) self.emit('uint4 bt%x = %s;' % (self.pc or 0, call)) for i in range(4): self.set_v(dst[1] + i, 'bt%x.%s' % (self.pc or 0, 'xyzw'[i])) @@ -11097,6 +11108,80 @@ def read(fmt, data, offset): ' word3 == 0x80000000u && word2 >= 1u && word2 < 0x04000000u &&', ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', '}', + # A triangle node is 64 bytes: five float3 vertices at 0..59 and one ID dword at 60. + # The kind selects one of four 8-bit maps: two bits for i, two for j, and a base vertex + # triple from RADV's radv_bvh_triangle_node (Mesa 25.1.0 bvh/bvh.h, MIT). + 'float x2w_bvh_component(float3 value, uint axis) {', + ' return axis == 0u ? value.x : (axis == 1u ? value.y : value.z);', + '}', + 'uint x2w_bvh_triangle_index(uint kind, uint slot) {', + ' if (slot == 0u) return kind == 0u ? 0u : (kind == 1u ? 1u : 2u);', + ' if (slot == 1u) return kind == 0u ? 1u : (kind == 1u ? 3u : (kind == 2u ? 3u : 4u));', + ' if (slot == 2u) return kind == 0u ? 2u : (kind == 1u ? 2u : (kind == 2u ? 4u : 0u));', + ' return 0u;', + '}', + 'float3 x2w_bvh_triangle_vertex(ByteAddressBuffer nodes, uint offset, uint kind, uint slot) {', + ' uint at = offset + 12u * x2w_bvh_triangle_index(kind, slot);', + ' return float3(asfloat(nodes.Load(at)), asfloat(nodes.Load(at + 4u)),', + ' asfloat(nodes.Load(at + 8u)));', + '}', + 'float3 x2w_bvh_shear(float3 vertex, float3 origin, float sx, float sy, float sz,', + ' uint kx, uint ky, uint kz) {', + ' float3 rel = vertex - origin;', + ' float rx = x2w_bvh_component(rel, kx);', + ' float ry = x2w_bvh_component(rel, ky);', + ' float rz = x2w_bvh_component(rel, kz);', + ' return float3(rx - sx * rz, ry - sy * rz, sz * rz);', + '}', + # Triangle return mode 1 (bit 120) is the only triangle mode this slice lowers. The box + # return mode is zero and is checked separately by each box helper. + 'bool x2w_bvh_triangle_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', + ' return (word1 & 0x7fffff00u) == 0u && (word3 & 0x0fffffffu) == 0x01000000u &&', + ' (word3 >> 28u) == 8u && word2 >= 1u && word2 < 0x04000000u &&', + ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', + '}', + 'uint4 x2w_bvh_intersect_triangle(ByteAddressBuffer nodes, uint node, uint word0, uint word1,', + ' uint word2, uint word3, float3 origin, float3 direction,', + ' float3 inv_dir) {', + ' uint4 miss = uint4(0x7f800000u, 0x3f800000u, 0u, 0u);', + ' uint kind = node & 7u;', + ' if (kind > 3u || !x2w_bvh_triangle_descriptor_ok(word0, word1, word2, word3)) return miss;', + ' uint offset = (node & 0xfffffff8u) << 3u;', + ' if ((offset >> 6u) + 1u > word2) return miss;', + ' uint id = nodes.Load(offset + 60u);', + ' uint id_byte = (id >> (8u * kind)) & 0xffu;', + ' uint i = id_byte & 3u;', + ' uint j = (id_byte >> 2u) & 3u;', + ' uint first = (3u - i - j) & 3u;', + ' float3 a = x2w_bvh_triangle_vertex(nodes, offset, kind, first);', + ' float3 b = x2w_bvh_triangle_vertex(nodes, offset, kind, i);', + ' float3 c = x2w_bvh_triangle_vertex(nodes, offset, kind, j);', + ' float3 ad = abs(direction);', + ' uint kz;', + ' if (ad.x >= ad.y) kz = ad.x >= ad.z ? 0u : 2u;', + ' else kz = ad.y >= ad.z ? 1u : 2u;', + ' uint kx = (kz + 1u) % 3u;', + ' uint ky = (kx + 1u) % 3u;', + ' if (x2w_bvh_component(direction, kz) < 0.0) {', + ' uint swap = kx; kx = ky; ky = swap;', + ' }', + ' float sz = x2w_bvh_component(inv_dir, kz);', + ' float sx = x2w_bvh_component(direction, kx) * sz;', + ' float sy = x2w_bvh_component(direction, ky) * sz;', + ' float3 sa = x2w_bvh_shear(a, origin, sx, sy, sz, kx, ky, kz);', + ' float3 sb = x2w_bvh_shear(b, origin, sx, sy, sz, kx, ky, kz);', + ' float3 sc = x2w_bvh_shear(c, origin, sx, sy, sz, kx, ky, kz);', + ' float u = sc.x * sb.y - sc.y * sb.x;', + ' float v = sa.x * sc.y - sa.y * sc.x;', + ' float w = sb.x * sa.y - sb.y * sa.x;', + ' bool behind = u < 0.0 || v < 0.0 || w < 0.0;', + ' bool before = u > 0.0 || v > 0.0 || w > 0.0;', + ' float det = u + (v + w);', + ' float t = (u * sa.z + v * sb.z) + w * sc.z;', + ' bool ahead = (det > 0.0 && t >= 0.0) || (det < 0.0 && t <= 0.0);', + ' if ((behind && before) || !ahead) return miss;', + ' return uint4(asuint(t), asuint(det), asuint(v), asuint(w));', + '}', # One FP32 box from a radv_bvh_box32_node (Mesa 25.1.0 bvh/bvh.h, MIT): children[4] at # bytes 0..15, coords[4][2][3] at 16..111 (lo then hi per child) and reserved at 112..127. 'float x2w_bvh_box32_slot(ByteAddressBuffer nodes, uint node_offset, uint index, float extent,', From 3ac44c2861b190e6635229a04e4d704872cf8e5e Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 16:03:48 +0000 Subject: [PATCH 09/44] startup: treat the BVH descriptor size as a count minus one Size 0 is a one-unit span, so a binary16 node at offset zero accepts it and an FP32 node needs size 1 at offset zero. Use the decoded extent in the Python guard and both HLSL helpers, with exact-fit, too-short, upper-bound and boundary-dispatch controls. --- .../experiments/startup-gfx2hlsl-bvh-box32.md | 3 +- tests/startup_gfx2hlsl_bvh_check.py | 102 +++++++++++++++++- tools/startup/gfx2hlsl.py | 11 +- 3 files changed, 106 insertions(+), 10 deletions(-) diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md index e598f60279..21acc67961 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-box32.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -25,7 +25,8 @@ in `min.x`. - `image_bvh_intersect_ray v[4], v[11], s[4]` with the packed address form (the disassembler prints `v[16:31]` for the eleven consumed dwords); - a constant inline T# built by four SGPR constants, type 8, nonzero encoded base, box growing zero, - size that covers the node (one 64-byte unit for binary16, two for FP32) and below 4 GiB; + size field (a count minus one in 64-byte units) whose decoded extent covers the node (one unit + for binary16, two for FP32; `size=0` is a one-unit span) and below 4 GiB; - a constant node pointer whose low three bits are 4 (64-byte aligned) or 5 (128-byte aligned) and inside the same 4 GiB relative address window; the entire node must fit within the 48-bit absolute address space; - either value of the sort bit. diff --git a/tests/startup_gfx2hlsl_bvh_check.py b/tests/startup_gfx2hlsl_bvh_check.py index 5e7cfbdd40..9d04c1ef2d 100644 --- a/tests/startup_gfx2hlsl_bvh_check.py +++ b/tests/startup_gfx2hlsl_bvh_check.py @@ -398,10 +398,27 @@ def controls(): and " bvh base " not in pipe.manifest() and "x2w_bvh_intersect_box16" not in wrap_hlsl and "uint4 bt" not in wrap_hlsl, str(refusals)) + # Size is a count minus one in 64-byte units. These are exact fits and one unit short. + for node, word2, label in ((0x04, 0, "box16 at offset zero in a one-unit span"), + (0x05, 1, "box32 at offset zero in a two-unit span"), + (0x0c, 1, "box16 in the last unit of a two-unit span")): + pipe, hlsl, refusals = translate_program(node=node, word2=word2) + check("exact-fit %s translates" % label, pipe is not None and not refusals, str(refusals)) + for node, word2, label in ((0x05, 0, "box32 at offset zero in a one-unit span"), + (0x0c, 0, "box16 in the last unit of a one-unit span")): + pipe, hlsl, refusals = translate_program(node=node, word2=word2) + check("too-short %s refuses" % label, + len(refusals) == 1 and "outside descriptor size" in refusals[0], str(refusals)) + pipe, hlsl, refusals = translate_program(node=0x04, word2=0x03ffffff) + check("largest decoded extent translates", pipe is not None and not refusals, str(refusals)) + pipe, hlsl, refusals = translate_program(node=0x04, word2=0x04000000) + check("extent above 4 GiB refuses", len(refusals) == 1 and "above 4 GiB" in refusals[0], str(refusals)) + # Portable checks ensure the actual emitted helpers and every negative # mutation are present even when a GPU dispatch is unavailable. + pipe, hlsl, refusals = translate_program(node=0x04) helpers = "\n".join(G.BVH_HELPERS) - check("translated shader embeds both dispatch-tested helpers", hlsl is not None and helpers in hlsl, "") + check("translated shader embeds both dispatch-tested helpers", pipe is not None and helpers in hlsl, "") for mutation in MUTATIONS: dispatch_hlsl(mutation) @@ -418,9 +435,9 @@ def controls(): ("descriptor type", dict(word3=0x60000000), "descriptor type 6 is not 8"), ("box growing", dict(word1=SORT_ENABLE | (2 << 23)), "box growing amount 2"), ("reserved word 1", dict(word1=SORT_ENABLE | 0x100), "reserved word 1"), - ("size zero", dict(word2=0), "does not cover the node"), + ("box32 size zero", dict(word2=0), "outside descriptor size"), ("node outside size", dict(node=0x25, word2=3), "outside descriptor size"), - ("box16 node outside size", dict(node=0x54, word2=10), "outside descriptor size"), + ("box16 node outside size", dict(node=0x54, word2=9), "outside descriptor size"), ("absolute base", dict(word0=0, word1=0), "absolute node base"), ("size high bits", dict(word3=RESOURCE_TYPE | 0x100), "size above 4 GiB"), ] @@ -544,13 +561,81 @@ def dispatch_hlsl(mutation=None): return "\n".join(lines) + "\n" +BOUNDARY_BOX32_OFFSET = 128 +BOUNDARY_RESULT_OFFSET = 256 +BOUNDARY_BUFFER_SIZE = 320 + + +def boundary_hlsl(): + helpers = "\n".join(G.BVH_HELPERS).replace("ByteAddressBuffer", "RWByteAddressBuffer") + lines = [helpers, "RWByteAddressBuffer data : register(u0);", "[numthreads(1, 1, 1)]", "void main() {"] + for i, (child, lo, hi) in enumerate(HALF_NODES[0]): + lines.append(" data.Store(%du, 0x%08xu);" % (4 * i, child)) + packed = struct.unpack("<3I", struct.pack("<6e", *lo, *hi)) + for j, word in enumerate(packed): + lines.append(" data.Store(%du, 0x%08xu);" % (16 + 12 * i + 4 * j, word)) + for i, (child, lo, hi) in enumerate(NODES[0]): + base = BOUNDARY_BOX32_OFFSET + lines.append(" data.Store(%du, 0x%08xu);" % (base + 4 * i, child)) + for j in range(3): + lines.append(" data.Store(%du, %s);" % (base + 16 + 24 * i + 4 * j, fbits(lo[j]))) + lines.append(" data.Store(%du, %s);" % (base + 16 + 24 * i + 12 + 4 * j, fbits(hi[j]))) + for j in range(4): + lines.append(" data.Store(%du, 0u);" % (base + 112 + 4 * j)) + lines.append(" DeviceMemoryBarrierWithGroupSync();") + box16_ray = HALF_RAYS[0] + box32_ray = RAYS[0] + cases = ( + (0, "x2w_bvh_intersect_box16", 0x04, 0, box16_ray[2:5], box16_ray[-1]), + (1, "x2w_bvh_intersect_box16", 0x0c, 0, box16_ray[2:5], (INVALID,) * 4), + (2, "x2w_bvh_intersect_box32", 0x15, 3, box32_ray[2:5], box32_ray[-1]), + (3, "x2w_bvh_intersect_box32", 0x15, 2, box32_ray[2:5], (INVALID,) * 4), + ) + expected = [] + for case, helper, pointer, word2, ray, result in cases: + extent, origin, direction = ray + inv = tuple(1.0 / c for c in direction) + lines.append( + " uint4 b%d = %s(data, 0x%08xu, 0x1000u, 0x80000000u, 0x%08xu, 0x80000000u, " + "%s, float3(%s, %s, %s), float3(%s, %s, %s));" % ( + case, helper, pointer, word2, ffloat(extent), ffloat(origin[0]), ffloat(origin[1]), + ffloat(origin[2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) + for word in range(4): + lines.append(" data.Store(%du, b%d.%s);" % (BOUNDARY_RESULT_OFFSET + 16 * case + 4 * word, case, "xyzw"[word])) + expected.append(result) + lines.append("}") + return "\n".join(lines) + "\n", expected + + +def run_boundary_dispatch(dxc, runner, adapter, directory): + source = directory / "bvh_boundary.hlsl" + cso = directory / "bvh_boundary.cso" + output = directory / "bvh_boundary.bin" + hlsl, expected = boundary_hlsl() + source.write_text(hlsl, encoding="ascii") + compiled = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + capture_output=True, text=True) + if compiled.returncode or compiled.stderr: + raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) + result = subprocess.run([runner, adapter, "--raw-uav-dump", str(cso), "1", str(BOUNDARY_BUFFER_SIZE), str(output)], + capture_output=True, text=True) + print(result.stdout, end="") + if result.returncode == 77: + return 77, None, expected + if result.returncode or result.stderr: + raise AssertionError(result.stderr or "offscreen_check exited with %d" % result.returncode) + data = output.read_bytes() + assert len(data) == BOUNDARY_BUFFER_SIZE, (len(data), BOUNDARY_BUFFER_SIZE) + return 0, struct.unpack("<%dI" % (len(data) // 4), data), expected + + def run_dispatch(dxc, runner, adapter, directory, mutation=None): name = "bvh_dispatch_" + mutation if mutation else "bvh_dispatch" source = directory / (name + ".hlsl") cso = directory / (name + ".cso") output = directory / (name + ".bin") source.write_text(dispatch_hlsl(mutation), encoding="ascii") - compiled = subprocess.run([dxc, "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], + compiled = subprocess.run([dxc, "-Gis", "-T", "cs_6_0", "-E", "main", "-Fo", str(cso), str(source)], capture_output=True, text=True) if compiled.returncode or compiled.stderr: raise AssertionError(compiled.stderr or "dxc exited with %d" % compiled.returncode) @@ -597,6 +682,15 @@ def check_dispatch(dxc, runner, adapter): changed = tuple(mutant[start:start + 4]) check("dispatch %s control changes %s" % (mutation, witness), changed != cases[case]["expected"], "got %s" % ["%08x" % w for w in changed]) + status, boundary_words, boundary_expected = run_boundary_dispatch(dxc, runner, adapter, directory) + if status == 77: + print("dispatch boundary: skip (adapter unavailable)") + return 77 + for case, wanted in enumerate(boundary_expected): + start = BOUNDARY_RESULT_OFFSET // 4 + 4 * case + got = tuple(boundary_words[start:start + 4]) + check("decoded descriptor extent case %d" % case, got == wanted, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in wanted])) if failures: print("FAILED: %s" % ", ".join(failures)) return 1 diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index a4dc8dc125..543c28952e 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -8111,9 +8111,10 @@ def op_image_bvh_intersect_ray(self, ops, mods): if base == 0: raise Unsupported('%s absolute node base is not lowered' % name) if vals[2] is not None: - if vals[2] < 1 or vals[2] >= 0x04000000: - raise Unsupported('%s descriptor size %d does not cover the node' % (name, vals[2])) - if (node_offset >> 6) + (node_bytes >> 6) > vals[2]: + if vals[2] >= 0x04000000: + raise Unsupported('%s descriptor size %d is above 4 GiB' % (name, vals[2])) + # Size is a count minus one in 64-byte units, so size=0 is a one-unit span. + if (node_offset >> 6) + (node_bytes >> 6) - 1 > vals[2]: raise Unsupported('%s node base %#x is outside descriptor size %d' % (name, node_offset, vals[2])) if base + node_offset + node_bytes > 1 << 48: raise Unsupported('%s node address wraps the 48-bit address space' % name) @@ -11094,7 +11095,7 @@ def read(fmt, data, offset): # slice does not bind, so it is refused here as a miss rather than read at address zero. 'bool x2w_bvh_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', ' return (word1 & 0x7fffff00u) == 0u &&', - ' word3 == 0x80000000u && word2 >= 1u && word2 < 0x04000000u &&', + ' word3 == 0x80000000u && word2 < 0x04000000u &&', ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', '}', # One FP32 box from a radv_bvh_box32_node (Mesa 25.1.0 bvh/bvh.h, MIT): children[4] at @@ -11188,7 +11189,7 @@ def read(fmt, data, offset): ' uint4 miss = uint4(X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS, X2W_BVH_MISS);', ' if ((node & 7u) != 4u || !x2w_bvh_descriptor_ok(word0, word1, word2, word3)) return miss;', ' uint offset = (node & 0xfffffff8u) << 3u;', - ' if ((offset >> 6u) + 1u > word2) return miss;', + ' if ((offset >> 6u) > word2) return miss;', ' inv_dir = clamp(inv_dir, -3.402823466e+38, 3.402823466e+38);', ' bool h0, h1, h2, h3;', ' float d0 = x2w_bvh_box16_slot(nodes, offset, 0u, extent, origin, inv_dir, h0);', From 070b12de185a426e2ec045b077c0c4a8954139e9 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 16:08:26 +0000 Subject: [PATCH 10/44] startup: use the decoded BVH extent for triangle nodes Size is a count minus one in 64-byte units: size 0 covers a triangle at offset zero, while a triangle in the next unit needs size 1. Cover exact fits, a too-short neighbor, the 4 GiB upper bound and the HLSL boundary dispatch on WARP and hardware. --- .../startup-gfx2hlsl-bvh-triangle.md | 6 +- tests/startup_gfx2hlsl_bvh_triangle_check.py | 76 ++++++++++++++++++- tools/startup/gfx2hlsl.py | 4 +- 3 files changed, 80 insertions(+), 6 deletions(-) diff --git a/docs/experiments/startup-gfx2hlsl-bvh-triangle.md b/docs/experiments/startup-gfx2hlsl-bvh-triangle.md index c5b8691f6e..5eeb202be9 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-triangle.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-triangle.md @@ -34,13 +34,15 @@ The accepted slice uses: - compute stage only; - `image_bvh_intersect_ray v[4], v[11], s[4]` with the packed address form; - a constant inline T# built by four SGPR constants, type 8, nonzero encoded base, box growing zero, - size at least one 64-byte unit and below 4 GiB; + size field (a count minus one in 64-byte units) whose decoded extent covers the node; `size=0` is + a one-unit span, and the field stays below 4 GiB; - a constant node pointer whose low three bits are 0..3 and whose address is inside the descriptor size and the 48-bit absolute address space; - either value of the sort bit; it is ignored for triangles. The manifest still names the allocation with `srv bvh base 0x size 0x`, using the -decoded byte address for `base`. The host binding of that line remains outside this change. +decoded byte address for `base`. The host binds `(size + 1) * 64` bytes. That binding remains +outside this change. ## Refused by name diff --git a/tests/startup_gfx2hlsl_bvh_triangle_check.py b/tests/startup_gfx2hlsl_bvh_triangle_check.py index a2c749f9f4..f2748c502b 100644 --- a/tests/startup_gfx2hlsl_bvh_triangle_check.py +++ b/tests/startup_gfx2hlsl_bvh_triangle_check.py @@ -87,12 +87,24 @@ def controls(): check("translated triangle shader embeds the dispatch-tested helpers", hlsl is not None and helpers in hlsl, "") + # Size is a count minus one in 64-byte units. A triangle uses one unit. + for node, word2, label in ((0x00, 0, "triangle at offset zero in a one-unit span"), + (0x08, 1, "triangle in the last unit of a two-unit span")): + pipe, hlsl, refusals = translate_triangle(node=node, word2=word2) + check("exact-fit %s translates" % label, pipe is not None and not refusals, str(refusals)) + pipe, hlsl, refusals = translate_triangle(0x08, word2=0) + check("too-short triangle in the last unit of a one-unit span refuses", + len(refusals) == 1 and "outside descriptor size" in refusals[0], str(refusals)) + pipe, hlsl, refusals = translate_triangle(0x00, word2=0x03ffffff) + check("largest decoded extent translates", pipe is not None and not refusals, str(refusals)) + pipe, hlsl, refusals = translate_triangle(0x00, word2=0x04000000) + check("extent above 4 GiB refuses", len(refusals) == 1 and "above 4 GiB" in refusals[0], str(refusals)) + cases = [ ("triangle return mode 0", dict(node=0x00, word3=RESOURCE_TYPE), "does not match node kind 0"), ("box return mode 1", dict(node=0x05, word3=RESOURCE_TYPE | TRIANGLE_MODE), "does not match node kind 5"), ("unknown node kind", dict(node=0x06), "node kind 6"), - ("size zero", dict(node=0x00, word2=0), "does not cover the node"), - ("node outside size", dict(node=0x20, word2=4), "outside descriptor size"), + ("node outside size", dict(node=0x20, word2=3), "outside descriptor size"), ("absolute base", dict(node=0x00, word0=0, word1=0), "absolute node base"), ("loaded descriptor", dict(node=0x00, loaded_descriptor=True), "loaded at run time"), ("descriptor type", dict(node=0x00, word3=0x60000000), "descriptor type 6 is not 8"), @@ -230,6 +242,57 @@ def dispatch_hlsl(mutation=None): return "\n".join(lines) + "\n" +TRIANGLE_BOUNDARY_RESULT_OFFSET = 64 +TRIANGLE_BOUNDARY_BUFFER_SIZE = 96 + + +def boundary_hlsl(): + witness = TRIANGLES[0] + helpers = "\n".join(G.BVH_HELPERS).replace("ByteAddressBuffer", "RWByteAddressBuffer") + lines = [helpers, "RWByteAddressBuffer data : register(u0);", "[numthreads(1, 1, 1)]", "void main() {"] + for i in range(16): + lines.append(" data.Store(%du, 0x%08xu);" % (4 * i, struct.unpack_from(" 0, str(changed)) + status, boundary_words, boundary_expected = run_boundary_dispatch(dxc, runner, adapter, directory) + if status == 77: + print("dispatch boundary: skip (adapter unavailable)") + return 77 + for case, wanted in enumerate(boundary_expected): + start = TRIANGLE_BOUNDARY_RESULT_OFFSET // 4 + 4 * case + got = tuple(boundary_words[start:start + 4]) + check("triangle decoded extent case %d" % case, got == wanted, + "got %s expected %s" % (["%08x" % w for w in got], ["%08x" % w for w in wanted])) if failures: print("FAILED: %s" % ", ".join(failures)) return 1 diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 66645699af..c59f66dd0f 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -11138,7 +11138,7 @@ def read(fmt, data, offset): # return mode is zero and is checked separately by each box helper. 'bool x2w_bvh_triangle_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', ' return (word1 & 0x7fffff00u) == 0u && (word3 & 0x0fffffffu) == 0x01000000u &&', - ' (word3 >> 28u) == 8u && word2 >= 1u && word2 < 0x04000000u &&', + ' (word3 >> 28u) == 8u && word2 < 0x04000000u &&', ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', '}', 'uint4 x2w_bvh_intersect_triangle(ByteAddressBuffer nodes, uint node, uint word0, uint word1,', @@ -11148,7 +11148,7 @@ def read(fmt, data, offset): ' uint kind = node & 7u;', ' if (kind > 3u || !x2w_bvh_triangle_descriptor_ok(word0, word1, word2, word3)) return miss;', ' uint offset = (node & 0xfffffff8u) << 3u;', - ' if ((offset >> 6u) + 1u > word2) return miss;', + ' if ((offset >> 6u) > word2) return miss;', ' uint id = nodes.Load(offset + 60u);', ' uint id_byte = (id >> (8u * kind)) & 0xffu;', ' uint i = id_byte & 3u;', From 2ce9f112c8dbe2a123558c0e118a97537e6ce63f Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 16:53:26 +0000 Subject: [PATCH 11/44] compile_dxil: invalidate a published manifest by sidecar content, not mtime The watcher treated a pixel-input sidecar as current whenever its timestamp was not newer than the manifest, so a content change with a preserved or older mtime kept a stale accepted manifest. Publish an FNV-1a digest of the .psin/.ps57in bytes next to the manifest and compare it before a cache hit; the batch graphics path writes the same digest. Regression: native_startup_request_cache_check.py now covers an unchanged cache hit, a contradictory .ps57in both older and newer than the manifest, and a changed .psin with a preserved mtime. Refs #3133. Refs #3091. --- tests/native_startup_request_cache_check.py | 65 +++++++++++++++++++- tools/startup/compile_dxil.cpp | 67 ++++++++++++++++++++- 2 files changed, 130 insertions(+), 2 deletions(-) diff --git a/tests/native_startup_request_cache_check.py b/tests/native_startup_request_cache_check.py index f6154395bb..4ca1424eab 100644 --- a/tests/native_startup_request_cache_check.py +++ b/tests/native_startup_request_cache_check.py @@ -301,7 +301,70 @@ def expect_graphics_refusal(label: str, setup, expected_stderr: str) -> None: assert not (bad_cs_dir / f"{bad_cs_key:016x}.txt").exists() assert not (bad_cs_dir / f"{bad_cs_key:016x}.cs.cso").exists() - print("native_startup_request_cache controls: current and archived graphics (.psin) + compute (.c67) cache entries and 8 refusal controls passed") + # 7. Watch invalidation: sidecar content, not its timestamp, decides whether a published manifest is current. + watch_cache = work / "watch-sidecar" + watch_cache.mkdir() + watch_key = put_graphics_request(watch_cache, VS_WORDS, ps_words(4), g_root, TARGET_MASKS) + watch_manifest = watch_cache / f"{watch_key:016x}.txt" + watch_psin = watch_cache / f"req_{watch_key:016x}.psin" + watch_sidecar = watch_cache / f"req_{watch_key:016x}.ps57in" + watch_fail = watch_cache / f"{watch_key:016x}.fail" + watch_digest = watch_cache / f"{watch_key:016x}.psinh" + + def run_watch() -> list[str]: + result = subprocess.run( + [cli, "--watch", sdk, frontend, watch_cache, "--once"], + capture_output=True, text=True, + ) + assert result.returncode == 0, (result.stdout, result.stderr) + return result.stdout.splitlines() + + first_lines = run_watch() + assert any(line.endswith(": compiled graphics") for line in first_lines), first_lines + assert watch_manifest.is_file() and watch_digest.is_file() + published_ns = watch_manifest.stat().st_mtime_ns + + # Unchanged sidecar bytes: the published manifest is a cache hit and is not rewritten. + second_lines = run_watch() + assert not any("compiled graphics" in line for line in second_lines), second_lines + assert watch_manifest.stat().st_mtime_ns == published_ns + + # A contradictory slot-57 sidecar with an older mtime must withdraw the stale manifest. + conflicting = b"PSI1" + struct.pack("(data); + for (size_t i = 0; i < size; ++i) { + hash ^= bytes[i]; + hash *= 1099511628211ull; + } +} + +static bool pixel_sidecar_hash(const fs::path& marker, std::string& digest) { + uint64_t hash = 1469598103934665603ull; + bool any = false; + for (const auto& path : {fs::path(marker).replace_extension(L".psin"), + fs::path(marker).replace_extension(L".ps57in")}) { + std::error_code ec; + if (!fs::is_regular_file(path, ec)) + continue; + std::ifstream file(path, std::ios::binary); + if (!file) + return false; + const std::vector bytes((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + const auto name = path.extension().wstring(); + sidecar_hash_bytes(hash, name.data(), name.size() * sizeof(wchar_t)); + const uint64_t count = bytes.size(); + sidecar_hash_bytes(hash, &count, sizeof(count)); + sidecar_hash_bytes(hash, bytes.data(), bytes.size()); + any = true; + } + if (!any) + return false; + char text[17]{}; + std::snprintf(text, sizeof(text), "%016llx", static_cast(hash)); + digest = text; + return true; +} + +static bool read_published_digest(const fs::path& path, std::string& digest) { + std::ifstream file(path, std::ios::binary); + if (!file) + return false; + digest.assign((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + return !digest.empty(); +} + static void publish_atomic(const fs::path& destination, const void* data, size_t size) { static std::atomic serial{}; auto temp=destination; @@ -717,7 +762,16 @@ static bool is_watch_request_pending(const fs::path& request_dir, const WatchReq const bool has_manifest = fs::is_regular_file(manifest_path, ec); if (has_manifest && !lost) { const auto manifest_mtime = fs::last_write_time(manifest_path, ec); - if (!ec && !(psin_mtime.has_value() && *psin_mtime > manifest_mtime)) { + bool sidecar_changed = false; + if (!req.compute) { + std::string sidecar_digest; + if (pixel_sidecar_hash(req.marker, sidecar_digest)) { + std::string published_digest; + sidecar_changed = !read_published_digest(fs::path(stem) += L".psinh", published_digest) || + published_digest != sidecar_digest; + } + } + if (!ec && !sidecar_changed && !(psin_mtime.has_value() && *psin_mtime > manifest_mtime)) { if (req.compute) { if (has_complete_dxbc(fs::path(stem) += L".cs.cso")) return false; @@ -816,6 +870,11 @@ static const char* compile_watch_item(x2w::ShaderDxilCompiler& compiler, const f publish_atomic(psdep_path, input.pixel_input_description.data(), input.pixel_input_description.size()); else fs::remove(psdep_path, ignored); + std::string sidecar_digest; + if (pixel_sidecar_hash(req.marker, sidecar_digest)) + publish_atomic(fs::path(stem) += L".psinh", sidecar_digest.data(), sidecar_digest.size()); + else + fs::remove(fs::path(stem) += L".psinh", ignored); publish_atomic(manifest_path, manifest->data(), manifest->size()); fs::remove(fail_path, ignored); return "compiled graphics"; @@ -1085,6 +1144,7 @@ int wmain(int argc, wchar_t** argv) { if(graphics_batch) { reserve_output(fs::path(stems[i]) += L".ps.cso"); reserve_output(fs::path(stems[i]) += L".psdep"); + reserve_output(fs::path(stems[i]) += L".psinh"); if(rectangles) reserve_output(fs::path(stems[i]) += L".gs.cso"); } } @@ -1141,6 +1201,11 @@ int wmain(int argc, wchar_t** argv) { if (manifest) { if (!input.pixel_input_description.empty()) publish_atomic(psdep_path, input.pixel_input_description.data(), input.pixel_input_description.size()); + std::string sidecar_digest; + if (pixel_sidecar_hash(inputs[i], sidecar_digest)) + publish_atomic(fs::path(stems[i]) += L".psinh", sidecar_digest.data(), sidecar_digest.size()); + else + fs::remove(fs::path(stems[i]) += L".psinh", ignored); publish_atomic(manifest_path, manifest->data(), manifest->size()); } fs::remove(fs::path(stems[i]) += L".fail", ignored); From 06c7380b733333b1e7c2a0d95c2a103ef345a8bf Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 16:52:07 +0000 Subject: [PATCH 12/44] runtime: keep the published disk pair after candidate PSO failure A native graphics candidate reports ready=1 before pipeline_for creates its desktop PSO. When CreateGraphicsPipelineState failed, the draw returned null and cached that result, so the target stayed clear even when a valid published pair existed in the shader cache. Reload that pair for the same render-target key, bump a translation revision so earlier native PSOs are not reused, and refuse the draw with a diagnostic when the pair is missing or invalid. Native-only mode keeps its explicit refusal. The published manifest and stage files are read, never rewritten. Refs #3134 --- src/startup_stubs/d3d12_draw.inl | 56 ++++++++++++--- tests/startup_native_graphics_draw_check.py | 77 ++++++++++++++++++++- 2 files changed, 121 insertions(+), 12 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index b1f4ff385c..4f9c12d5a3 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -175,6 +175,9 @@ struct Translation { x2w_startup::ComPtr indexed_signature; std::unordered_map pipelines; // by target formats u64 key = 0; + bool native_candidate = false; // shaders and manifest were prepared in-process; a published disk pair may also exist + u64 revision = 0; // bumped when a disk pair replaces the native shaders, invalidating created PSOs + std::string rtv_request; // the RTV variant text this translation was prepared for, else empty LONG logged_draws = 0, logged_bindings = 0, logged_large = 0; // diagnostics budget per translation }; @@ -287,7 +290,7 @@ bool native_shaders_only() return enabled; } -void load_translation(Translation& tr, const std::string& rtv_request = {}, std::string manifest = {}) +void load_translation(Translation& tr, const std::string& rtv_request = {}, std::string manifest = {}, bool count = true) { tr.state = 2; if (manifest.empty() && native_shaders_only()) { @@ -298,7 +301,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: const bool provided = !manifest.empty(); if (!cache_path(path, L"", tr.key, L".txt")) return; if (!provided && !read_text(path, manifest)) { - if (!tr.manifest_retry.pending()) { + if (count && !tr.manifest_retry.pending()) { InterlockedIncrement(&translation_missing); static LONG missing; if (rtv_request.empty() && first_calls(missing, 12)) @@ -418,8 +421,8 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}, std: return; } tr.state = 1; - if (previously_missing) InterlockedDecrement(&translation_missing); - InterlockedIncrement(&translation_ready); + if (count && previously_missing) InterlockedDecrement(&translation_missing); + if (count) InterlockedIncrement(&translation_ready); log("x2w-draw pipeline %016llx translated: %zu entry values, %zu resources, %zu writable textures, %zu static samplers, sampler_heap=%u", tr.key, tr.uds.size(), tr.srvs.size(), tr.uavs.size(), tr.samplers.statics.size(), tr.samplers.heap ? 1u : 0u); } @@ -452,6 +455,7 @@ static bool try_native_graphics(Translation& tr, bool variant = false) auto ps = stage(pair.pixel.dxil_ir, L"ps_6_6", ps_hit); Translation candidate; candidate.key = tr.key; + candidate.rtv_request = request.rtv_request; if (!pair.input_layout.empty()) { try { candidate.fixed_rectangle_ir = x2w::native_rectangle_geometry(pair.vertex.outputs, pair.pixel.inputs); } catch (const x2w::UnsupportedComputeShader&) {} // Triangle lists and strips still use the original pair. @@ -467,6 +471,7 @@ static bool try_native_graphics(Translation& tr, bool variant = false) } candidate.vs = vs.Detach(); candidate.ps = ps.Detach(); + candidate.native_candidate = true; tr = std::move(candidate); log("x2w-draw native graphics %016llx ready=%u cache(frontend,vs,ps)=%u,%u,%u", tr.key, tr.state == 1, frontend_hit, vs_hit, ps_hit); @@ -1099,6 +1104,7 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) if (!entry) { entry = new Translation; entry->key = key; + entry->rtv_request = request; #ifdef X2W_NATIVE_SHADERS if (GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr, 0) && publish_shader_request(key, L".rtv", request.data(), request.size()) && try_native_graphics(*entry, true)) return entry; @@ -1131,6 +1137,7 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P if (use_depth_stencil) key = fnv_bytes(&bound.depth_stencil, sizeof(bound.depth_stencil), key); if (bound.has_rasterizer) key = fnv_bytes(&bound.rasterizer, sizeof(bound.rasterizer), key); key = fnv_bytes(&indexed_rect, sizeof(indexed_rect), key); + if (tr.revision) key = fnv_bytes(&tr.revision, sizeof(tr.revision), key); const auto found = bound.pipelines.find(key); if (found != bound.pipelines.end()) return found->second; D3D12_GRAPHICS_PIPELINE_STATE_DESC desc{}; @@ -1204,11 +1211,42 @@ ID3D12PipelineState* pipeline_for(BoundPipeline& bound, Translation& tr, const P desc.SampleDesc.Count = 1; ID3D12PipelineState* pipeline = nullptr; X2W_ZONE("desktop pipeline creation"); - const HRESULT hr = device_of(the_device)->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)); - log("x2w-draw desktop pipeline for %016llx, %u targets (format %d) -> 0x%08lx (dsv %d, depth %d)", tr.key, - pass.target_count, pass.target_count ? pass.target_formats[0] : 0, static_cast(hr), - static_cast(dsv_format), desc.DepthStencilState.DepthEnable ? 1 : 0); - check_device("translated CreateGraphicsPipelineState", 0); + HRESULT hr = E_FAIL; + const bool injected = tr.native_candidate && x2w_local::env_on("X2W_TEST_NATIVE_GRAPHICS_PSO_FAILURE"); + if (!injected) { + hr = device_of(the_device)->CreateGraphicsPipelineState(&desc, IID_PPV_ARGS(&pipeline)); + log("x2w-draw desktop pipeline for %016llx, %u targets (format %d) -> 0x%08lx (dsv %d, depth %d)", tr.key, + pass.target_count, pass.target_count ? pass.target_formats[0] : 0, static_cast(hr), + static_cast(dsv_format), desc.DepthStencilState.DepthEnable ? 1 : 0); + check_device("translated CreateGraphicsPipelineState", 0); + } + if (FAILED(hr) && pipeline) { + pipeline->Release(); + pipeline = nullptr; + } + if (FAILED(hr) && tr.native_candidate) { + // A native candidate whose shaders this device cannot turn into a PSO keeps the published pair usable. + log("x2w-draw native graphics %016llx candidate pipeline failed 0x%08lx%s", tr.key, + static_cast(hr), injected ? " (injected)" : ""); + if (!native_shaders_only()) { + Translation fallback; + fallback.key = tr.key; + fallback.rtv_request = tr.rtv_request; + load_translation(fallback, tr.rtv_request, {}, false); + if (fallback.state == 1) { + fallback.revision = tr.revision + 1; + tr = std::move(fallback); + log("x2w-draw native graphics %016llx published disk pair recovered", tr.key); + ID3D12PipelineState* recovered = pipeline_for(bound, tr, pass, indexed_rect); + if (!recovered) + log("x2w-draw native graphics %016llx published disk pair pipeline failed", tr.key); + return recovered; + } + log("x2w-draw native graphics %016llx no valid published disk pair", tr.key); + } else { + log("x2w-draw native graphics %016llx no published disk pair in native-only mode", tr.key); + } + } bound.pipelines[key] = pipeline; return pipeline; } diff --git a/tests/startup_native_graphics_draw_check.py b/tests/startup_native_graphics_draw_check.py index 5b0bd18a11..51cde53e9d 100644 --- a/tests/startup_native_graphics_draw_check.py +++ b/tests/startup_native_graphics_draw_check.py @@ -10,6 +10,12 @@ from startup_stream_draw_check import vop1, vop2 +def assert_debug_clean(stderr): + for line in stderr.splitlines(): + if "x2w-d3d12-debug " in line: + assert " sev=0 " not in line and " sev=1 " not in line, line + + def triangle(): code = [vop2(0x1a, 1, 129, 0), vop2(0x1b, 1, 130, 1), vop2(0x1b, 2, 130, 0)] for v in (1, 2): @@ -24,7 +30,7 @@ def check(folder, consumer, sdk, adapter, compiler): vs, ps, root, pixels = [folder / name for name in ("vs", "ps", "root", "pixels")] vs.write_bytes(triangle()) ps.write_bytes(patched_pixel(2, [vop1(1, 0, 128), vop1(1, 1, 242)], export=(0xf800180f, 0x01000001))) - env = dict(os.environ, X2W_SHADER_CACHE=str(cache), X2W_NATIVE_SHADERS=sdk, + env = dict(os.environ, X2W_SHADER_CACHE=str(cache), X2W_NATIVE_SHADERS=sdk, X2W_NATIVE_SHADERS_ONLY="0", X2W_D3D12_DEBUG="1", X2W_D3D12_RENDER="1", X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1") clear = bytes((0, 0, 255, 255)) red = bytes((255, 0, 0, 255)) @@ -47,7 +53,7 @@ def check(folder, consumer, sdk, adapter, compiler): subprocess.run([compiler, "--watch", sdk, cache, cache, "--once"], check=True, timeout=45) marker, = cache.glob("req_*.a") manifest = cache / (marker.stem.removeprefix("req_") + ".txt") - published = {p: p.read_bytes() for p in + published = {p: (p.read_bytes(), p.stat().st_mtime_ns) for p in (manifest, manifest.with_suffix(".vs.cso"), manifest.with_suffix(".ps.cso"))} for fault, diagnostic in (("MANIFEST", "unsupported manifest version"), ("ROOT", "failed 0x80004005")): manifest.rename(str(manifest) + ".pending") @@ -60,8 +66,73 @@ def check(folder, consumer, sdk, adapter, compiler): assert run.returncode == 0 and diagnostic in run.stderr and "-> drawn;" in run.stderr, run.stderr assert first.read_bytes() == clear * 32 assert pixels.read_bytes() == (red * 4 + clear * 4) * 4 - assert all(path.read_bytes() == expected for path, expected in published.items()) + assert all(path.read_bytes() == expected[0] and path.stat().st_mtime_ns == expected[1] + for path, expected in published.items()) print(f"{adapter} {fault}: same-process fallback drew 16 red pixels after publication") + + # The published pair alone draws the target when native preparation is disabled. + pixels.unlink() + disk_env = {name: value for name, value in env.items() if name != "X2W_NATIVE_SHADERS"} + run = subprocess.run(args, env=disk_env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0, run.stderr + assert "native graphics" not in run.stderr and "-> drawn;" in run.stderr, run.stderr[-8000:] + assert_debug_clean(run.stderr) + assert pixels.read_bytes() == (red * 4 + clear * 4) * 4 + print(f"{adapter} disk pair: native disabled, 16 red and 16 clear pixels") + + # A candidate PSO failure falls back to that pair in the same draw, without rewriting it. + pso_env = dict(env, X2W_NATIVE_SHADERS_ONLY="0", X2W_TEST_NATIVE_GRAPHICS_PSO_FAILURE="1") + pixels.unlink() + run = subprocess.run(args, env=pso_env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0, run.stderr + assert "candidate pipeline failed 0x80004005 (injected)" in run.stderr, run.stderr[-8000:] + assert "published disk pair recovered" in run.stderr and "-> drawn;" in run.stderr, run.stderr[-8000:] + assert_debug_clean(run.stderr) + assert pixels.read_bytes() == (red * 4 + clear * 4) * 4 + assert all(path.read_bytes() == expected[0] and path.stat().st_mtime_ns == expected[1] + for path, expected in published.items()) + print(f"{adapter} PSO: candidate failure recovered the published disk pair, 16 red and 16 clear pixels") + + # The native path still creates its own pipeline when no fault is injected. + pixels.unlink() + run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0, run.stderr + assert "native graphics" in run.stderr and "ready=1 cache(frontend,vs,ps)=1,1,1" in run.stderr, run.stderr[-8000:] + assert "candidate pipeline failed" not in run.stderr and "refused:" not in run.stderr, run.stderr[-8000:] + assert "-> drawn;" in run.stderr, run.stderr[-8000:] + assert_debug_clean(run.stderr) + assert pixels.read_bytes() == (red * 4 + clear * 4) * 4 + print(f"{adapter} native: successful candidate still drew 16 red and 16 clear pixels") + + # A missing or invalid pair refuses the draw with a diagnostic rather than an all-clear target. + ps_cso = manifest.with_suffix(".ps.cso") + held_ps = Path(str(ps_cso) + ".hold") + ps_cso.rename(held_ps) + try: + pixels.unlink() + run = subprocess.run(args, env=pso_env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0, run.stderr + assert "no valid published disk pair" in run.stderr and "-> drawn;" not in run.stderr, run.stderr[-8000:] + assert pixels.read_bytes() == clear * 32 + print(f"{adapter} missing pair: refused with a diagnostic, 32 clear pixels") + finally: + held_ps.rename(ps_cso) + held_manifest = Path(str(manifest) + ".hold") + manifest.rename(held_manifest) + manifest.write_text("x2w-manifest 999\n") + try: + pixels.unlink() + run = subprocess.run(args, env=pso_env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0, run.stderr + assert "unsupported manifest version" in run.stderr, run.stderr[-8000:] + assert "no valid published disk pair" in run.stderr and "-> drawn;" not in run.stderr, run.stderr[-8000:] + assert pixels.read_bytes() == clear * 32 + print(f"{adapter} invalid pair: refused with a diagnostic, 32 clear pixels") + finally: + manifest.unlink() + held_manifest.rename(manifest) + assert all(path.read_bytes() == expected[0] and path.stat().st_mtime_ns == expected[1] + for path, expected in published.items()) ps.write_bytes(patched_pixel(1, [0xffffffff], export=(0xf800180f, 0x01000001))) run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45) assert run.returncode == 0 and "refused:" in run.stderr and "-> drawn;" not in run.stderr, run.stderr From e387d855f43ea69a15215e4a30850d1cffebf800 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 18:00:19 +0000 Subject: [PATCH 13/44] startup: identify a rotated rectangle corner by its diagonal (#3131) The indexed rectangle stage found the right-angle corner by testing whether a corner shares an x or a y with each of its neighbours. A rotated rectangle has no axis-aligned edge, so no corner matched, the stage returned without emitting either triangle, and the region the rectangle covered stayed unpainted with the rectangle diagonal as its boundary. The vertex-stage rectangle expansion has no such restriction (it uses v0 + v2 - v1 directly), so the two implementations of the same rule disagreed. The corner is now also identified from the shape: the right-angle corner is the vertex opposite the diagonal, the longest of the three edges, and the two sides must meet at a right angle so a shape that is not a rectangle stays undrawn. The axis test keeps precedence, so every input it accepted is unchanged. Both startup_stubs/indexed_rect_geometry.h and the native rule of gfx1013_rect_geometry.cpp use it. tests/startup_rect_geometry.cpp draws one rectangle named by three corners with back-face culling on: the axis order and the swung order (rejected by winding) keep their previous result, and the same square turned by 15 degrees covers 0 of 32 differing pixels instead of 32. tests/startup_rect_gap.cpp and tests/startup_rect_gap_check.py add the reported synthetic draw: eight 12-byte records (mask at +0, XY at +4), two vertex-buffer views over the same records, an R16 indexed triangle list and a six-vertex rectangle list of the same quad and edge ring, a mask-controlled pixel shader and a constant-colour control, an RGBA8 target, and back-face culling. The bound vertex and index bytes, the translated fetch and the pre/post-draw pixels match the model in every mode, on WARP and through the hardware backend; the reported diagonal gap does not reproduce for that input (docs/experiments/startup-rect-gap.md). Refs #3131 --- CMakeLists.txt | 9 + docs/experiments/startup-rect-gap.md | 75 +++++ src/gfx1013_rect_geometry.cpp | 29 ++ src/startup_stubs/indexed_rect_geometry.h | 14 + tests/cmake/startup_rect_gap.cmake | 12 + tests/startup_rect_gap.cpp | 121 +++++++ tests/startup_rect_gap_check.py | 283 +++++++++++++++++ tests/startup_rect_geometry.cpp | 365 ++++++++++++++++++++++ tests/startup_stream_draw.cpp | 3 + tests/startup_stream_setup.cpp | 47 ++- 10 files changed, 953 insertions(+), 5 deletions(-) create mode 100644 docs/experiments/startup-rect-gap.md create mode 100644 tests/cmake/startup_rect_gap.cmake create mode 100644 tests/startup_rect_gap.cpp create mode 100644 tests/startup_rect_gap_check.py create mode 100644 tests/startup_rect_geometry.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 31a51f2c82..fcb6578b25 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1333,8 +1333,17 @@ target_sources(startup_stream_consumer PRIVATE tests/startup_frame_copy.cpp) target_sources(startup_stream_consumer PRIVATE tests/startup_root_reset.cpp) target_sources(startup_stream_consumer PRIVATE tests/startup_memory_srv_diag.cpp) target_sources(startup_stream_consumer PRIVATE tests/startup_pixel_uav.cpp) +target_sources(startup_stream_consumer PRIVATE tests/startup_rect_gap.cpp) target_sources(startup_stream_consumer PRIVATE tests/startup_slot67_indirect.cpp tests/desktop_gpu.cpp) +# The shared indexed rectangle-expansion stage (startup_stubs/indexed_rect_geometry.h) drawn on its own, with +# back-face culling on: the axis order, a swung order of the same corners and a rotated rectangle (#3131). +# tests/cmake/startup_rect_gap.cmake registers its tests and the runtime draw. +add_executable(startup_rect_geometry tests/startup_rect_geometry.cpp) +target_compile_features(startup_rect_geometry PRIVATE cxx_std_17) +target_include_directories(startup_rect_geometry PRIVATE src) +target_link_libraries(startup_rect_geometry PRIVATE d3d12 dxgi d3dcompiler) + add_executable(startup_stream_depth tests/startup_stream_depth.cpp $) target_compile_features(startup_stream_depth PRIVATE cxx_std_17) target_link_libraries(startup_stream_depth PRIVATE d3d12_xs_shim d3d12 dxgi) diff --git a/docs/experiments/startup-rect-gap.md b/docs/experiments/startup-rect-gap.md new file mode 100644 index 0000000000..f91e1205c1 --- /dev/null +++ b/docs/experiments/startup-rect-gap.md @@ -0,0 +1,75 @@ +# The indexed rectangle rule and a 12-byte vertex stream (#3131) + +Issue #3131 reports that an indexed UI gradient draw leaves a sharply bounded region of its colour target +uncovered, with a diagonal boundary, and that the draw's recording-time vertex read uses a 12-byte stride. The +reported rule was checked against source-built input: an eight-vertex quad and edge ring, 12-byte vertex +records with XY at +4, an indexed triangle list, a mask-controlled pixel shader and an RGBA8 target, through +the runtime entry (`startup_stream_consumer`), plus a fixture for the shared rectangle-expansion stage alone. + +## What the runtime draw measured + +`tests/startup_rect_gap.cpp` (draw) and `tests/startup_rect_gap_check.py` (input, model and comparison) bind a +placed 12-byte-record stream twice, slot 0 as R32_FLOAT (the mask at +0) and slot 1 as R32G32_FLOAT at +4, and +draw four triangles: records 0-1-2 and 0-2-6 (the edge ring), then 3-4-5 and 3-5-7 (the inner quad), so the +same eight records serve an R16 indexed triangle list and a six-vertex rectangle list. A mask-controlled pixel +shader paints the quad red and the ring green; a constant-red pixel shader is the coverage control. The target +is cleared blue, and the check compares all 32 pixels with a point-in-triangle model of the two triangles. + +Every mode covered exactly the pixels the model expects, on WARP and through the `hardware` backend: + +| mode | draw | result | +|---|---|---| +| `triangle` / `triangle-copy` | R16 indexed list, placed stream / unregistered stream (recording-time copy and index scan) | 12 red, 20 green | +| `rect` / `rect8` / `rect8-copy` | six- and eight-vertex rectangle lists, expanded by the vertex stage | 12 red, 20 green | +| `rect8`, `triangle` with the constant shader | coverage only | 32 red | +| `triangle-rotated` / `rect-rotated` | the same rectangles turned by 15 degrees | 12 red, 18 green, 2 clear | +| `none` | no draw | 32 clear | + +The check also asserts the bound bytes (8 records of 12 bytes, then the 12 indices), the input-layout request +(`TEXCOORD 0 41 0 0 0 0` and `POSITION 0 16 1 4 0 0`), and the generated vertex stage's two loads, +`a = (vid + ud1) * ud3 + 4;` for POSITION and `a = (vid + ud1) * ud4 + 0;` for the mask. With +`X2W_TEST_RASTERIZER=back` (back-face culling, clockwise front) the picture is unchanged, and with `back-ccw` +(counter-clockwise front) every triangle is culled and the target stays clear, so the winding survives the +expansion. The described diagonal gap did not appear in any of these draws. + +## The one stage that did leave a region uncovered + +`tests/startup_rect_geometry.cpp` compiles the shared rule (`src/startup_stubs/indexed_rect_geometry.h`) the way +the runtime does, binds it with back-face culling on, and draws one rectangle named by three corners. Its +`axis` order was covered exactly; its `rotated` order, the same square turned by 15 degrees, was dropped whole: +32 of 32 pixels kept the clear colour. The rule located the right-angle corner by looking for a corner that +shares an x or a y with each of its neighbours, so a rectangle with no axis-aligned edge matched no corner and +the stage returned without emitting either triangle. The vertex-stage rectangle expansion never had that +restriction: it uses `v0 + v2 - v1` directly, so the two implementations of the same rule disagreed, and a +rotated UI rectangle lost both of its triangles. + +The fix identifies the same corner from the shape: the right-angle corner is the vertex opposite the diagonal, +which is the longest of the three edges, and the two sides must also meet at a right angle. Both +`indexed_rect_geometry.h` and the native rule in `src/gfx1013_rect_geometry.cpp` now use it, with the axis test +keeping precedence, so every input the old rule accepted is unchanged. After the fix `axis`, `swung` (the same +square in another corner order, which back-face culling rejects by its winding) and `rotated` all match the +model: 0 of 32 pixels differ. + +## Commands and environment + +```powershell +ctest --preset dev --no-tests=error -R '^(startup_rect_geometry|startup_rect_gap)_(warp|hardware)$' -V +ctest --preset dev --no-tests=error -R '^(startup_indirect_translated_indexed_rect|startup_indirect_rectlist|native_direct_container|rectlist_topology|rectlist_draw)_(warp|hardware)?$' +``` + +Measured on Windows 11 build 26300, MSVC 19.44.35228, Windows SDK 10.0.26100.0 (DXC 10.0.26100.0), at +`63a30dc1` with this change on top. `startup_rect_geometry` ran on WARP (Microsoft Basic Render Driver +10.0.26100.10068) and on the AMD Radeon RX 9060 XT (driver 32.0.32029.2010). The runtime draw reported the +Microsoft Basic Render Driver in both of its backends, so its picture is a WARP result. The D3D12 debug layer is +not installed on this machine (`D3D12GetDebugInterface` fails), so the fixtures report `debug_layer=unavailable` +and no debug-layer messages were collected. + +## What remains open + +Which draw produced the reported gap is not established. A stream renamed by a view that declares fewer bytes +than the indices name draws nothing at all here (both the placed view and the recording-time copy stop at the +declared size), so that is a separate, unverified candidate. The indexed rectangle stage is only reached through +an indirect draw, and two of its paths are not covered by these fixtures: a translated non-indexed indirect +rectangle list keeps the title's three-vertices-per-rectangle count (the vertex stage then draws half of the +rectangles), and the stage's flat (`FPARAM`) outputs take the value of the first vertex for both triangles +instead of each triangle's provoking vertex. Neither was exercised here. diff --git a/src/gfx1013_rect_geometry.cpp b/src/gfx1013_rect_geometry.cpp index 82429d4d6b..b3107ee723 100644 --- a/src/gfx1013_rect_geometry.cpp +++ b/src/gfx1013_rect_geometry.cpp @@ -79,6 +79,35 @@ std::string native_rectangle_geometry(const std::vector &output corner[i] = both(either(both(x, y), both(other_x, other_y)), both(compare("one", a[0], b[0]), compare("one", a[1], b[1]))); } + // A rotated rectangle has no corner that shares an axis with a neighbour, so the axis test above misses it + // and the whole rectangle would be dropped (#3131). The right-angle corner is the vertex opposite the + // rectangle's diagonal, the longest of its three edges: for corner c with neighbours a and b, |a - b| is the + // diagonal and is longer than both sides. The sides must also meet at a right angle, so a shape that is not a + // rectangle stays undrawn. The axis corners keep precedence, as they did before. + auto squared = [&](const string &p, const string &q) { + auto d = ir.value("fsub float " + p + ", " + q); + return ir.value("fmul float " + d + ", " + d); + }; + const auto distance2 = [&](const std::array &p, const std::array &q) { + auto dx = squared(p[0], q[0]), dy = squared(p[1], q[1]); + return ir.value("fadd float " + dx + ", " + dy); + }; + std::array geometric; + for (unsigned i = 0; i < 3; ++i) { + auto &p = position[i], &a = position[(i + 1) % 3], &b = position[(i + 2) % 3]; + auto across = distance2(a, b), to_a = distance2(p, a), to_b = distance2(p, b); + // (p - a) . (p - b), squared, against 1e-6 of |p - a|^2 |p - b|^2: the two sides meet at a right angle. + auto diff = [&](const string &u, const string &v) { return ir.value("fsub float " + u + ", " + v); }; + auto times = [&](const string &u, const string &v) { return ir.value("fmul float " + u + ", " + v); }; + auto dot = ir.value("fadd float " + times(diff(p[0], a[0]), diff(p[0], b[0])) + ", " + + times(diff(p[1], a[1]), diff(p[1], b[1]))); + auto limit = ir.value("fmul float " + times(to_a, to_b) + ", 1.000000e-06"); + geometric[i] = both(both(compare("ogt", across, to_a), compare("ogt", across, to_b)), + compare("ole", times(dot, dot), limit)); + } + auto any_axis = either(corner[0], either(corner[1], corner[2])); + for (unsigned i = 0; i < 3; ++i) + corner[i] = either(corner[i], both(ir.value("xor i1 " + any_axis + ", true"), geometric[i])); valid = both(valid, either(corner[0], either(corner[1], corner[2]))); // Only a non-degenerate rectangle has a unique matching corner. for (auto &c : channels) { diff --git a/src/startup_stubs/indexed_rect_geometry.h b/src/startup_stubs/indexed_rect_geometry.h index c2b6e77df2..84219483c1 100644 --- a/src/startup_stubs/indexed_rect_geometry.h +++ b/src/startup_stubs/indexed_rect_geometry.h @@ -72,6 +72,17 @@ bool corner_between(float2 p, float2 a, float2 b) { return (p.x == a.x && p.y == b.y && p.y != a.y && p.x != b.x) || (p.x == b.x && p.y == a.y && p.y != b.y && p.x != a.x); } +// The right-angle corner is the vertex opposite the rectangle's diagonal, which is the longest of its three +// edges: for the corner c with neighbours a and b, |a - b| is the diagonal and is longer than both sides. The +// axis test above is one case of this; a rotated rectangle has no corner that shares an axis with a neighbour, +// so without this test the stage drops it and leaves the region it covers unpainted (#3131). The two sides must +// also meet at a right angle, so a shape that is not a rectangle stays undrawn as before. +bool corner_off_longest(float2 p, float2 a, float2 b) { + float2 pa = p - a, pb = p - b, ab = a - b; + const float across = dot(ab, ab), side_a = dot(pa, pa), side_b = dot(pb, pb); + const float angle = dot(pa, pb); + return across > side_a && across > side_b && angle * angle <= 1e-6 * side_a * side_b; +} [maxvertexcount(6)] void main(triangle Vertex input[3], inout TriangleStream stream) { Vertex v[3] = input; @@ -80,6 +91,9 @@ void main(triangle Vertex input[3], inout TriangleStream stream) { uint corner = 3; [unroll] for (uint i = 0; i < 3; ++i) if (corner_between(v[i].pos.xy, v[(i + 1) % 3].pos.xy, v[(i + 2) % 3].pos.xy)) corner = i; + if (corner == 3) + [unroll] for (uint j = 0; j < 3; ++j) + if (corner_off_longest(v[j].pos.xy, v[(j + 1) % 3].pos.xy, v[(j + 2) % 3].pos.xy)) corner = j; if (corner == 3) return; uint a = (corner + 1) % 3, b = (corner + 2) % 3; )"; diff --git a/tests/cmake/startup_rect_gap.cmake b/tests/cmake/startup_rect_gap.cmake new file mode 100644 index 0000000000..08a094566e --- /dev/null +++ b/tests/cmake/startup_rect_gap.cmake @@ -0,0 +1,12 @@ +# The eight-vertex quad-and-edge-ring draw with 12-byte vertex records (#3131): the shared indexed rectangle +# expansion with back-face culling on, and the same draw through the startup runtime entry. +add_test(NAME startup_rect_geometry_warp COMMAND startup_rect_geometry) +add_test(NAME startup_rect_geometry_hardware COMMAND startup_rect_geometry hardware) +set_tests_properties(startup_rect_geometry_hardware PROPERTIES SKIP_RETURN_CODE 77) + +foreach(backend IN ITEMS warp hardware) + add_test(NAME startup_rect_gap_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}" + "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_rect_gap_check.py" + "$" "${backend}") + set_tests_properties(startup_rect_gap_${backend} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) +endforeach() diff --git a/tests/startup_rect_gap.cpp b/tests/startup_rect_gap.cpp new file mode 100644 index 0000000000..626111ef27 --- /dev/null +++ b/tests/startup_rect_gap.cpp @@ -0,0 +1,121 @@ +// X2W_TEST_RECT_GAP (#3131): the eight-vertex quad-and-edge-ring draw. +// +// Every vertex record is 12 bytes: a binary32 mask at +0, then XY at +4. Two vertex-buffer views name +// the same records, slot 0 (TEXCOORD, R32_FLOAT at offset 0, the mask) and slot 1 (POSITION, +// R32G32_FLOAT at offset 4), both with a 12-byte stride. Records 0-2 are the edge ring that encloses the +// quad (mask 0) and 3-5 the inner quad (mask 1); 6 and 7 are their fourth corners, so a rectangle list of +// six vertices and an indexed triangle list built from the same bytes describe the same four triangles. +// The ring is drawn first, so the quad's diagonal stays visible. A mask-controlled pixel shader paints +// the quad red and the ring green; a constant-colour pixel shader paints whatever the geometry covers red. +// +// triangle R16 indexed triangle list, ring then quad (12 indices: 0-1-2, 0-2-6, 3-4-5, 3-5-7) +// triangle-copy the same draw from a vertex stream and an index view that no placed buffer holds, +// so the recording-time vertex read and the index scan size the copy +// rect non-indexed rectangle list of six vertices (the ring and the quad) +// rect8 the same rectangle list with eight vertices, two of them unused +// rect8-copy the eight-vertex rectangle list from an unregistered vertex stream +// none no draw: the cleared target, read back through the same path +// +// X2W_TEST_RECT_GAP_BYTES names a file that receives the vertex bytes the draw bound, then the index +// bytes it bound, so the check can compare them with what it wrote. +#include + +#include +#include +#include +#include +#include + +#include "startup_stream_setup.h" + +namespace { +using Word = std::uint64_t; +template Word arg(T* value) { return reinterpret_cast(value); } + +struct Vertex { + float mask, x, y; +}; +// Each rectangle is three corners clockwise on screen (bottom-left, top-left, top-right); the fourth +// corner of a rectangle is v0 + v2 - v1 and is stored at 6 and 7. +constexpr std::array vertices{{ + {0.0f, -1.0f, -1.0f}, {0.0f, -1.0f, 1.0f}, {0.0f, 1.0f, 1.0f}, // ring + {1.0f, -0.75f, -0.625f}, {1.0f, -0.75f, 0.625f}, {1.0f, 0.75f, 0.625f}, // quad + {0.0f, 1.0f, -1.0f}, {1.0f, 0.75f, -0.625f}, // the fourth corners +}}; +constexpr std::array indices{{0, 1, 2, 0, 2, 6, 3, 4, 5, 3, 5, 7}}; + +// Memory no placed buffer covers: the draw then copies the bytes it needs while recording. +alignas(64) unsigned char unplaced[256]; +} + +int draw_rect_gap(void* guest, void* list) +{ + char mode[32]{}; + if (!GetEnvironmentVariableA("X2W_TEST_RECT_GAP", mode, sizeof(mode))) return 2; + // The stream harness scissors an 8x4 target to its left half by default; this draw covers the whole + // target, so both sides of each diagonal are read back. + const D3D12_RECT whole{0, 0, 8, 4}; + invoke(list, 22, 1, arg(&whole)); + if (std::strcmp(mode, "none") == 0) return 0; + const bool indexed = std::strcmp(mode, "triangle") == 0 || std::strcmp(mode, "triangle-copy") == 0; + const bool short_view = std::strcmp(mode, "triangle-short") == 0; + const bool copied = std::strstr(mode, "-copy") != nullptr; + const bool rotated = std::strstr(mode, "rotated") != nullptr; + const bool indexed_path = indexed || short_view || std::strcmp(mode, "triangle-rotated") == 0; + if (!indexed_path && std::strncmp(mode, "rect", 4) != 0) return 2; + + // A rotation keeps the parallelogram, so v0 + v2 - v1 is still its fourth corner, but no corner shares + // an axis with its two neighbours any more. + std::array records = vertices; + if (rotated) { + const float angle = 0.2617993877991494f; // 15 degrees + const float c = std::cos(angle), s = std::sin(angle); + for (Vertex& v : records) { + const float x = v.x, y = v.y; + v.x = c * x - s * y; + v.y = s * x + c * y; + } + } + + void* const placed = VirtualAlloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!placed) return 43; + unsigned char* const vertex_bytes = copied ? unplaced : static_cast(placed); + unsigned char* const index_bytes = static_cast(placed) + 0x2000; + std::memcpy(vertex_bytes, records.data(), sizeof(records)); + std::memcpy(index_bytes, indices.data(), sizeof(indices)); + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = 0x10000; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + void* resource = nullptr; + if (FAILED(static_cast(invoke(guest, 133, arg(static_cast(placed)), arg(&desc), + D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&resource))))) return 44; + // triangle-short declares a three-record view although its indices name records up to seven: desktop IA + // reads the bytes the indices name, so the quad still has to be covered. + const UINT view_bytes = short_view ? 3 * sizeof(Vertex) : static_cast(sizeof(records)); + const D3D12_VERTEX_BUFFER_VIEW views[2] = { + {arg(vertex_bytes), view_bytes, sizeof(Vertex)}, {arg(vertex_bytes), view_bytes, sizeof(Vertex)}}; + invoke(list, 48, 0, 2, arg(views)); + if (indexed_path) { + // The quad's indices, 3-4-5 and 3-5-7, follow the ring's six. + const UINT index_offset = short_view ? 12 : 0; + const D3D12_INDEX_BUFFER_VIEW index_view{arg(index_bytes + index_offset), + static_cast(sizeof(indices)) - index_offset, + DXGI_FORMAT_R16_UINT}; + invoke(list, 47, arg(&index_view)); + invoke(list, 20, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + invoke(list, 13, static_cast(std::size(indices)) - index_offset / 2, 1, 0, 0, 0); + } else { + invoke(list, 20, 17 /* D3D_PRIMITIVE_TOPOLOGY_RECTLIST, the console topology value */); + invoke(list, 12, std::strncmp(mode, "rect8", 5) == 0 ? 8 : 6, 1); + } + char dump[MAX_PATH]{}; + const DWORD length = GetEnvironmentVariableA("X2W_TEST_RECT_GAP_BYTES", dump, MAX_PATH); + if (length && length < MAX_PATH) { + std::ofstream file(dump, std::ios::binary); + file.write(reinterpret_cast(vertex_bytes), sizeof(records)); + if (indexed_path) file.write(reinterpret_cast(index_bytes), sizeof(indices)); + } + return 0; +} diff --git a/tests/startup_rect_gap_check.py b/tests/startup_rect_gap_check.py new file mode 100644 index 0000000000..690429a37c --- /dev/null +++ b/tests/startup_rect_gap_check.py @@ -0,0 +1,283 @@ +"""The eight-vertex quad-and-edge-ring draw of #3131, with a 12-byte vertex record and XY at +4. + +Source-built gfx1013 code only. The vertex stage calls the driver's fetch routine: two records, POSITION +(register 0, mask 0x7) read as R32G32_FLOAT at +4 of a 12-byte record and TEXCOORD (register 1, mask 0x1) +read as R32_FLOAT at +0. The stream's input layout therefore names slot 0 TEXCOORD R32_FLOAT at offset 0 and +slot 1 POSITION R32G32_FLOAT at offset 4, and both views name the same records with a 12-byte stride. + +Records 0-2 are the edge ring that encloses the quad (mask 0) and 3-5 the inner quad (mask 1); 6 and 7 are +their fourth corners, so a rectangle list of six vertices and an indexed triangle list built from the same +bytes describe the same four triangles. The ring is drawn first, so the quad's diagonal stays visible. Two +pixel shaders read the same draw: + mask: interpolates TEXCOORD (the mask) and paints the quad red and the ring green, so every pixel + says which region covered it and a missing triangle leaves the clear colour. + constant: exports opaque red without reading an input, so a gap here would be a coverage gap and a gap + only in the mask picture would be an attribute or interpolation gap. + +Draws, each read back as 32 RGBA pixels: + triangle R16 indexed triangle list, ring then quad + triangle-copy the same draw from a stream and index view no placed buffer holds: the recording-time + vertex read and the index scan size what is copied + rect non-indexed rectangle list of six vertices + rect8 the eight-vertex rectangle list (the last two vertices are not part of a rectangle) + rect8-copy the eight-vertex rectangle list from an unregistered stream + none no draw: the cleared target +The rect modes use the six-vertex expansion the vertex stage applies to a rectangle list. With +X2W_TEST_RASTERIZER=back the same picture must come back with back-face culling on, and =back-ccw +(counter-clockwise front faces) must cull the whole draw: that is the winding control. +""" +import os +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import zlib +import math + +from startup_stream_check import gfx2hlsl +from startup_stream_draw_check import vop1, vop2 + +WIDTH, HEIGHT = 8, 4 +BLUE, RED, GREEN = bytes((0, 0, 255, 255)), bytes((255, 0, 0, 255)), bytes((0, 255, 0, 255)) +VS_BASE, PS_BASE = 0x2f8, 0xef8 +FETCH_CALL, PREFETCH, WAIT_VM, ENDPGM = 0xbe842104, 0xbfa00003, 0xbf8c3f70, 0xbf810000 + +# mask, x, y per 12-byte record. Each rectangle is three corners clockwise on screen; 6 and 7 hold the +# fourth corner v0 + v2 - v1, which the indexed list names and the rectangle list derives. +VERTICES = [(0.0, -1.0, -1.0), (0.0, -1.0, 1.0), (0.0, 1.0, 1.0), + (1.0, -0.75, -0.625), (1.0, -0.75, 0.625), (1.0, 0.75, 0.625), + (0.0, 1.0, -1.0), (1.0, 0.75, -0.625)] +INDICES = [0, 1, 2, 0, 2, 6, 3, 4, 5, 3, 5, 7] +TRIANGLES = [(0, 1, 2), (0, 2, 6), (3, 4, 5), (3, 5, 7)] +ROTATED = math.radians(15.0) +LAYOUT_TEXT = "ia1 2\nTEXCOORD 0 41 0 0 0 0\nPOSITION 0 16 1 4 0 0\n" +LAYOUT_LINE = "x2w-draw stream input layout: 2 elements (format/slot/offset/class) 41/0/0/0 16/1/4/0" + + +def signature(tag, entries): + names, body = b"", b"" + first = 8 + 32 * len(entries) + for name, index, register, system, mask in entries: + body += struct.pack("<6IBBHI", 0, first + len(names), index, system, 3, register, mask, mask, 0, 0) + names += name.encode("ascii") + b"\0" + data = struct.pack(" mask; red where the mask is 1, green where it is 0. + words = [0xc8080000, 0xc8090001, vop1(1, 0, 128), vop1(1, 1, 242), + 0x7c0804f0, # v_cmp_gt_f32 vcc_lo, 0.5, v2 + vop2(1, 3, 256 + 1, 0), # v3 = vcc ? v0 : v1 (red) + vop2(1, 4, 256 + 0, 1), # v4 = vcc ? v1 : v0 (green) + 0xf800180f, 0x01000403, # exp mrt0 v3, v4, v0, v1 done vm + ENDPGM] + inputs = [("SV_POSITION", 0, 0, 1, 0xf), ("TEXCOORD", 0, 2, 0, 0x1)] + return container(0, words, PS_BASE, [signature(b"ISG1", inputs)], + {0x138: bytes((6, 2, 0x1, 0, 0, 0, 2, 2)), 0x238: struct.pack(" 1e-3, f"pixel ({x}, {y}) lies on an edge of {triangle}" + if not (any(e < 0 for e in edges) and any(e > 0 for e in edges)): + hit = "quad" if triangle[0] >= 3 else "ring" + return hit + + +def expected(mask, rotated=False): + out = bytearray() + for y in range(HEIGHT): + for x in range(WIDTH): + covered = region(x, y, rotated) + out += (BLUE if covered is None else RED if (covered == "quad" or not mask) else GREEN) + return bytes(out) + + +def describe(image): + """Counts of each colour, so a failure says which region moved.""" + names = {BLUE: "clear", RED: "red", GREEN: "green"} + counts = {} + for i in range(0, len(image), 4): + name = names.get(image[i:i + 4], image[i:i + 4].hex()) + counts[name] = counts.get(name, 0) + 1 + return ", ".join(f"{n} {c}" for n, c in sorted(counts.items())) + + +def first_difference(actual, want): + for i in range(0, len(want), 4): + if actual[i:i + 4] != want[i:i + 4]: + return "pixel (%d, %d) is %s, expected %s" % (i // 4 % WIDTH, i // 4 // WIDTH, + actual[i:i + 4].hex(), want[i:i + 4].hex()) + return None + + +class Run: + def __init__(self, directory, consumer, mode, mask, rasterizer=None): + directory.mkdir(parents=True) + self.cache = directory / "cache" + self.cache.mkdir() + self.output = directory / "pixels" + self.bound = directory / "bound" + vs, ps, root = directory / "vs", directory / "ps", directory / "root" + vs.write_bytes(vertex()) + ps.write_bytes(pixel(mask)) + self.args = [consumer, str(vs), str(ps), str(root)] + self.env = dict(os.environ, X2W_D3D12_PERMISSIVE="1", X2W_D3D12_LIST_NOOP="1", X2W_D3D12_RENDER="1", + X2W_SHADER_CACHE=str(self.cache), X2W_TEST_INPUT_LAYOUT="gradient", + X2W_TEST_RECT_GAP=mode, X2W_TEST_RECT_GAP_BYTES=str(self.bound)) + self.env.setdefault("X2W_D3D12_DEBUG", "0") + if rasterizer: + self.env["X2W_TEST_RASTERIZER"] = rasterizer + else: + self.env.pop("X2W_TEST_RASTERIZER", None) + subprocess.run(self.args, env=self.env, check=True) + self.key = None + if mode != "none": + requests = sorted(self.cache.glob("req_*.a")) + assert len(requests) == 1, requests + self.key = int(requests[0].name[4:20], 16) + + def translate(self): + status = gfx2hlsl.translate_request(str(self.cache), self.key) + assert status == "ok", status + return self.cache / ("%016x.vs.hlsl" % self.key) + + def draw(self, backend): + result = subprocess.run(self.args + [backend, str(self.output)], env=self.env, capture_output=True, text=True) + for line in result.stderr.splitlines(): + if line.startswith("adapter=") or "debug layer:" in line: + print(" " + line) + return result + + +def check(directory, consumer, backend, rasterizer=None): + # The clear colour, before any draw. + plain = Run(directory / "none", consumer, "none", True) + result = plain.draw(backend) + if result.returncode == 77: + print("No D3D12 feature-level 12 adapter") + return 77 + if result.returncode: + raise RuntimeError(f"none failed on {backend}: {result.returncode}\n{result.stderr}") + if plain.output.read_bytes() != BLUE * (WIDTH * HEIGHT): + raise AssertionError("the cleared target is not the expected blue: " + describe(plain.output.read_bytes())) + print(f"{backend} none: 32 clear pixels, pre-draw state exact") + + for mode, mask in (("triangle", True), ("triangle", False), ("triangle-copy", True), + ("rect", True), ("rect8", True), ("rect8-copy", True), ("rect8", False), + ("triangle-rotated", True), ("rect-rotated", True)): + label = f"{mode} {'mask' if mask else 'constant'}" + rotated = "rotated" in mode + run = Run(directory / (label.replace(" ", "_") + ("_" + rasterizer if rasterizer else "")), consumer, + mode, mask, rasterizer) + hlsl = run.translate() + text = hlsl.read_text() + layout = (run.cache / ("req_%016x.ia" % run.key)).read_bytes() + assert layout == LAYOUT_TEXT.encode(), layout + # POSITION (slot 1, R32G32_FLOAT at +4) and the mask (slot 0, R32_FLOAT at +0), each scaled by its + # own stream stride. + for line in ("a = (vid + ud1) * ud3 + 4;", "a = (vid + ud1) * ud4 + 0;"): + assert " " + line + "\n" in text, line + "\n" + text + if mode.startswith("rect"): + for line in ("uint first = (vid / 6) * 3, corner = vid % 6;", "o.pos = p.pos + r.pos - q.pos;"): + assert line in text, line + "\n" + text + result = run.draw(backend) + if result.returncode == 77: + print("No D3D12 feature-level 12 adapter") + return 77 + if result.returncode or "-> drawn;" not in result.stderr: + raise RuntimeError(f"{label} failed on {backend}: {result.returncode}\n{result.stderr}") + if LAYOUT_LINE not in result.stderr: + raise AssertionError("missing layout diagnostic:\n" + result.stderr) + bound = run.bound.read_bytes() + records = placed(rotated) + got = struct.unpack("<24f", bound[:96]) + for i, (mask_value, x, y) in enumerate(records): + for name, actual, want in (("mask", got[3 * i], mask_value), ("x", got[3 * i + 1], x), + ("y", got[3 * i + 2], y)): + if abs(actual - want) > 1e-6: + raise AssertionError(f"{label}: record {i} {name} is {actual}, expected {want}") + if "triangle" in mode and bound[96:] != struct.pack("<%dH" % len(INDICES), *INDICES): + raise AssertionError(f"{label}: bound indices {bound[96:].hex()}") + actual = run.output.read_bytes() + want = expected(mask, rotated) + difference = first_difference(actual, want) + if difference: + raise AssertionError(f"{label}: {difference} ({describe(actual)})") + print(f"{backend} {label}: 32 pixels exact ({describe(actual)}); 8 records of 12 bytes bound") + return 0 + + +if __name__ == "__main__": + with tempfile.TemporaryDirectory() as temp: + args = sys.argv[1:] + rasterizer = args[2] if len(args) > 2 else None + sys.exit(check(Path(temp), *args[:2], rasterizer=rasterizer)) diff --git a/tests/startup_rect_geometry.cpp b/tests/startup_rect_geometry.cpp new file mode 100644 index 0000000000..c2dbcc4bfa --- /dev/null +++ b/tests/startup_rect_geometry.cpp @@ -0,0 +1,365 @@ +// The shared rectangle-expansion rule of src/startup_stubs/indexed_rect_geometry.h on a desktop device (#3131). +// +// The translated indexed rectangle draw binds this geometry stage, and the runtime compiles it from the +// vertex and pixel bytecode of the same translation. This fixture compiles the same rule and draws one +// rectangle that a rectangle list names with three corners, with back-face culling on, so the coverage it +// emits is measured directly: +// axis bottom-left, top-left, top-right: the corner test always finds a corner that shares an axis +// with each neighbour, and the fourth corner is v0 + v2 - v1 +// swung bottom-left, top-right, top-left: the same three corners in another order, which the stage +// normalises to the same square +// rotated the square turned by 15 degrees: still a parallelogram whose fourth corner is v0 + v2 - v1 after +// the right-angle corner is identified, and the corner the non-indexed path derives in the vertex +// stage. No corner shares an axis with its neighbours, so the axis test cannot identify it. +// Each vertex record is 12 bytes (a mask at +0, XY at +4) and both orders must cover the pixels the two +// triangles of the literal rule cover. Without an adapter argument the fixture uses WARP. +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "startup_stubs/indexed_rect_geometry.h" + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr UINT width = 8, height = 4; +constexpr DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM; +// R8G8B8A8 words: the low byte is red, then green and blue. +constexpr std::uint32_t red = 0xff0000ff, blue = 0xffff0000; + +struct Vertex { + float mask, x, y; +}; +static_assert(sizeof(Vertex) == 12); + +// The three corners of a rectangle, clockwise on screen (bottom-left, top-left, top-right). +constexpr std::array corners{{ + {1.0f, -1.0f, -1.0f}, {1.0f, -1.0f, 1.0f}, {1.0f, 1.0f, 1.0f}}}; + +int failures; +void expect(bool ok, const char* what) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +HRESULT compile(const char* source, const char* profile, ComPtr& blob) +{ + ComPtr errors; + const HRESULT hr = D3DCompile(source, std::strlen(source), "rect_geometry_fixture", nullptr, nullptr, "main", profile, + 0, 0, &blob, &errors); + if (FAILED(hr) && errors) std::printf("compile %s: %s\n", profile, static_cast(errors->GetBufferPointer())); + return hr; +} + +bool inside(const std::array, 3>& triangle, float x, float y, float& margin) +{ + float edges[3]; + for (int i = 0; i < 3; ++i) { + const auto& a = triangle[i]; + const auto& b = triangle[(i + 1) % 3]; + edges[i] = (b[0] - a[0]) * (y - a[1]) - (b[1] - a[1]) * (x - a[0]); + } + margin = (std::min)({std::fabs(edges[0]), std::fabs(edges[1]), std::fabs(edges[2])}); + const bool negative = edges[0] < 0 || edges[1] < 0 || edges[2] < 0; + const bool positive = edges[0] > 0 || edges[1] > 0 || edges[2] > 0; + return !(negative && positive); +} + +// The pixels the rectangle covers: (v0, v1, v2) and (v0, v2, v3) of its four corners. For the axis order this +// is the literal rule (v3 = v0 + v2 - v1); a swung order names the same four corners, which is the order the +// existing indirect fixture pins for the geometry stage. +std::vector reference(const std::array, 4>& quad) +{ + const auto at = [&](int i, int axis) { return axis ? quad[i].second : quad[i].first; }; + const std::array, 3> first{at(0, 0), at(0, 1), at(1, 0), at(1, 1), at(2, 0), at(2, 1)}; + const std::array, 3> second{at(0, 0), at(0, 1), at(2, 0), at(2, 1), at(3, 0), at(3, 1)}; + std::vector pixels(width * height, blue); // the clear colour + for (UINT y = 0; y < height; ++y) { + for (UINT x = 0; x < width; ++x) { + const float centre_x = (2.0f * x + 1.0f) / width - 1.0f; + const float centre_y = 1.0f - (2.0f * y + 1.0f) / height; + float margin = 0; + const bool covered = inside(first, centre_x, centre_y, margin) || inside(second, centre_x, centre_y, margin); + expect(margin > 1e-3f, "a pixel centre lies on a rectangle edge"); + pixels[y * width + x] = covered ? red : blue; + } + } + return pixels; +} +} + +int main(int argc, char** argv) +{ + const bool hardware = argc > 1 && std::strcmp(argv[1], "hardware") == 0; + ComPtr factory; + ComPtr adapter; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 4; + if (hardware) { + ComPtr factory6; + if (FAILED(factory.As(&factory6))) return 77; + for (UINT n = 0;; ++n) { + ComPtr candidate; + const HRESULT hr = factory6->EnumAdapterByGpuPreference(n, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&candidate)); + if (hr == DXGI_ERROR_NOT_FOUND) return 77; + if (FAILED(hr)) return 4; + DXGI_ADAPTER_DESC1 desc{}; + if (FAILED(candidate->GetDesc1(&desc))) return 4; + if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) continue; + if (SUCCEEDED(D3D12CreateDevice(candidate.Get(), D3D_FEATURE_LEVEL_12_0, __uuidof(ID3D12Device), nullptr))) { + adapter = candidate; + break; + } + } + } else if (FAILED(factory->EnumWarpAdapter(IID_PPV_ARGS(&adapter)))) { + return 4; + } + ComPtr device; + { + ComPtr debug; + const HRESULT hr = D3D12GetDebugInterface(IID_PPV_ARGS(&debug)); + if (SUCCEEDED(hr)) debug->EnableDebugLayer(); + std::printf("debug_layer=%s\n", SUCCEEDED(hr) ? "on" : "unavailable"); + } + if (FAILED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_12_0, IID_PPV_ARGS(&device)))) return 5; + DXGI_ADAPTER_DESC desc{}; + LARGE_INTEGER driver{}; + adapter->GetDesc(&desc); + adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &driver); + std::printf("adapter=%ls driver=%u.%u.%u.%u\n", desc.Description, HIWORD(driver.HighPart), LOWORD(driver.HighPart), + HIWORD(driver.LowPart), LOWORD(driver.LowPart)); + + // The vertex stage exports the 12-byte record's XY as the position, which is what the geometry stage reads + // back through its signature. The mask at +0 is not named by the layout: this fixture measures coverage. + static const char vs_text[] = R"( +struct In { float2 xy : POSITION; }; +float4 main(In input) : SV_Position { return float4(input.xy, 0, 1); })"; + static const char ps_text[] = R"( +float4 main(float4 pos : SV_Position) : SV_Target { return float4(1, 0, 0, 1); })"; + ComPtr vs, ps, gs, gs_errors; + if (FAILED(compile(vs_text, "vs_5_1", vs)) || FAILED(compile(ps_text, "ps_5_1", ps))) return 6; + if (FAILED(x2w_startup::compile_indexed_rect_geometry(vs.Get(), ps.Get(), &gs, &gs_errors))) { + if (gs_errors) std::printf("geometry: %s\n", static_cast(gs_errors->GetBufferPointer())); + return 7; + } + + const D3D12_INPUT_ELEMENT_DESC elements[] = { + {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 4, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + }; + // A pipeline state that sets an input layout needs this flag on its root signature. + D3D12_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; + ComPtr root_blob; + if (FAILED(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1_0, &root_blob, nullptr))) return 8; + ComPtr root; + if (FAILED(device->CreateRootSignature(0, root_blob->GetBufferPointer(), root_blob->GetBufferSize(), + IID_PPV_ARGS(&root)))) return 8; + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.Get(); + pso_desc.VS = {vs->GetBufferPointer(), vs->GetBufferSize()}; + pso_desc.GS = {gs->GetBufferPointer(), gs->GetBufferSize()}; + pso_desc.PS = {ps->GetBufferPointer(), ps->GetBufferSize()}; + pso_desc.InputLayout = {elements, 1}; + pso_desc.BlendState.RenderTarget[0] = {TRUE, FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, + D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, + D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL}; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_BACK; + pso_desc.RasterizerState.FrontCounterClockwise = FALSE; // clockwise on screen is front, as in the source + pso_desc.RasterizerState.DepthClipEnable = TRUE; + // A zero-filled depth-stencil description holds invalid enum values (stencil op 0), so the fields a + // depth-less pipeline still needs are spelled out. + pso_desc.DepthStencilState.DepthEnable = FALSE; + pso_desc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; + pso_desc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + pso_desc.DepthStencilState.StencilEnable = FALSE; + pso_desc.DepthStencilState.StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK; + pso_desc.DepthStencilState.StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK; + pso_desc.DepthStencilState.FrontFace = {D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, + D3D12_COMPARISON_FUNC_ALWAYS}; + pso_desc.DepthStencilState.BackFace = pso_desc.DepthStencilState.FrontFace; + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = format; + pso_desc.SampleDesc.Count = 1; + pso_desc.SampleMask = UINT_MAX; + ComPtr pso; + const HRESULT pso_hr = device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&pso)); + if (FAILED(pso_hr)) { + std::printf("CreateGraphicsPipelineState: 0x%08lx\n", static_cast(pso_hr)); + ComPtr queue; + if (SUCCEEDED(device.As(&queue))) { + const UINT64 count = queue->GetNumStoredMessages(); + for (UINT64 i = 0; i < count; ++i) { + SIZE_T size = 0; + queue->GetMessage(i, nullptr, &size); + std::vector message(size); + auto* entry = reinterpret_cast(message.data()); + if (SUCCEEDED(queue->GetMessage(i, entry, &size))) + std::printf("debug layer: %s\n", entry->pDescription); + } + } + return 9; + } + + D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_RESOURCE_DESC target_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, format, + {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const float clear[4] = {0, 0, 1, 1}; + const D3D12_CLEAR_VALUE optimized{format, {clear[0], clear[1], clear[2], clear[3]}}; + ComPtr target; + if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &target_desc, D3D12_RESOURCE_STATE_COMMON, + &optimized, IID_PPV_ARGS(&target)))) return 10; + D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + ComPtr rtv_heap; + if (FAILED(device->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtv_heap)))) return 10; + device->CreateRenderTargetView(target.Get(), nullptr, rtv_heap->GetCPUDescriptorHandleForHeapStart()); + + struct Scene { + const char* name; + std::array records; + // The four corners of the rectangle the three records name, clockwise on screen from the bottom left. + std::array, 4> quad; + float angle; + // False for the order whose winding the back-face test rejects: the stage must draw nothing for it. + bool covered; + }; + const auto turned = [](std::array rectangle, float degrees) { + const float c = std::cos(degrees * 3.14159265358979324f / 180.0f); + const float s = std::sin(degrees * 3.14159265358979324f / 180.0f); + for (Vertex& v : rectangle) { + const float x = v.x, y = v.y; + v.x = c * x - s * y; + v.y = s * x + c * y; + } + return rectangle; + }; + const std::array, 4> square{{ + {-1.0f, -1.0f}, {-1.0f, 1.0f}, {1.0f, 1.0f}, {1.0f, -1.0f}}}; + std::array, 4> turned_square = square; + { + const float c = std::cos(15.0f * 3.14159265358979324f / 180.0f); + const float s = std::sin(15.0f * 3.14159265358979324f / 180.0f); + for (auto& p : turned_square) p = {c * p.first - s * p.second, s * p.first + c * p.second}; + } + std::array scenes{{ + {"axis", {}, square, 0.0f, true}, + {"swung", {}, square, 0.0f, false}, + {"rotated", {}, turned_square, 15.0f, true}, + }}; + // The three corners a rectangle list names per rectangle: v0, v1 and v2. The fourth is derived. Both + // records of the six-vertex dispatch name the same rectangle. + const std::array, 3> records{{ + {corners[0], corners[1], corners[2]}, // bottom left, top left, top right + {corners[0], corners[2], corners[1]}, // bottom left, top right, top left + {turned(corners, 15.0f)[0], turned(corners, 15.0f)[1], turned(corners, 15.0f)[2]}, + }}; + for (auto& scene : scenes) { + const auto& three = records[&scene - scenes.data()]; + for (int i = 0; i < 3; ++i) scene.records[i] = three[i]; + for (int i = 0; i < 3; ++i) scene.records[3 + i] = three[i]; + } + + D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const auto make_buffer = [&](UINT64 bytes, D3D12_RESOURCE_STATES state, ID3D12Resource** out) { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, bytes, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + return device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, + IID_PPV_ARGS(out)); + }; + ComPtr vertices; + void* mapped = nullptr; + if (FAILED(make_buffer(sizeof(Scene::records), D3D12_RESOURCE_STATE_GENERIC_READ, &vertices)) || + FAILED(vertices->Map(0, nullptr, &mapped))) return 11; + UINT64 total = 0; + device->GetCopyableFootprints(&target_desc, 0, 1, 0, nullptr, nullptr, nullptr, &total); + ComPtr readback; + { + D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, total, 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; + if (FAILED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&readback)))) + return 12; + } + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + device->GetCopyableFootprints(&target_desc, 0, 1, 0, &footprint, nullptr, nullptr, &total); + + const D3D12_VIEWPORT viewport{0, 0, static_cast(width), static_cast(height), 0, 1}; + const D3D12_RECT scissor{0, 0, width, height}; + const D3D12_VERTEX_BUFFER_VIEW vertex_view{vertices->GetGPUVirtualAddress(), sizeof(Scene::records), sizeof(Vertex)}; + for (const auto& scene : scenes) { + std::memcpy(mapped, scene.records.data(), sizeof(scene.records)); + ComPtr allocator; + ComPtr list; + if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator))) || + FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.Get(), pso.Get(), IID_PPV_ARGS(&list)))) + return 13; + const auto transition = [&](ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + list->ResourceBarrier(1, &barrier); + }; + transition(target.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ClearRenderTargetView(rtv_heap->GetCPUDescriptorHandleForHeapStart(), clear, 0, nullptr); + list->OMSetRenderTargets(1, &rtv_heap->GetCPUDescriptorHandleForHeapStart(), FALSE, nullptr); + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->IASetVertexBuffers(0, 1, &vertex_view); + list->DrawInstanced(6, 1, 0, 0); + transition(target.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION to{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + to.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION from{target.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + transition(target.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + if (FAILED(list->Close())) return 14; + ComPtr queue; + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + ComPtr fence; + if (FAILED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence)))) return 15; + ID3D12CommandList* lists[]{list.Get()}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.Get(), 1))) return 15; + while (fence->GetCompletedValue() != 1) Sleep(1); + void* pixels = nullptr; + if (FAILED(readback->Map(0, nullptr, &pixels))) return 16; + std::vector actual(width * height); + for (UINT y = 0; y < height; ++y) + std::memcpy(&actual[y * width], static_cast(pixels) + y * footprint.Footprint.RowPitch, + width * 4); + readback->Unmap(0, nullptr); + auto want = reference(scene.quad); + if (!scene.covered) std::fill(want.begin(), want.end(), blue); + UINT differing = 0; + for (UINT i = 0; i < actual.size(); ++i) { + if (actual[i] != want[i]) { + if (!differing) + std::printf(" %s: pixel (%u, %d) is %08x, expected %08x\n", scene.name, i % width, + static_cast(i / width), actual[i], want[i]); + ++differing; + } + } + expect(differing == 0, scene.name); + std::printf("%s: %u of %u pixels differ from the literal rectangle rule (angle %.1f)\n", scene.name, differing, + width * height, scene.angle); + } + vertices->Unmap(0, nullptr); + std::printf("rect geometry: %s, %d failure(s)\n", failures ? "failed" : "passed", failures); + return failures ? 1 : 0; +} diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 8848ae1572..07e806c1f5 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -561,6 +561,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } else if (GetEnvironmentVariableW(L"X2W_TEST_ROOT_RESET", nullptr, 0)) { extern int draw_root_reset(void*, void*); if (const int result = draw_root_reset(guest, list)) return result; + } else if (GetEnvironmentVariableW(L"X2W_TEST_RECT_GAP", nullptr, 0)) { + extern int draw_rect_gap(void*, void*); + if (const int result = draw_rect_gap(guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_FRAME_COPY", nullptr, 0)) { extern int draw_frame_copies(ID3D12Device*, void*, void*, UINT, UINT); if (const int result = draw_frame_copies(desktop.Get(), guest, list, width, height)) return result; diff --git a/tests/startup_stream_setup.cpp b/tests/startup_stream_setup.cpp index c92d9b49ff..bf7b3c76f3 100644 --- a/tests/startup_stream_setup.cpp +++ b/tests/startup_stream_setup.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -35,6 +36,12 @@ struct alignas(8) Layout { D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; D3D12_INPUT_LAYOUT_DESC desc; }; +// X2W_TEST_RASTERIZER: a RASTERIZER subobject after the shaders, so a translated draw runs with the cull +// mode and front-face winding of the console pipeline instead of the default (no culling). +struct alignas(8) Raster { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE tag; + D3D12_RASTERIZER_DESC desc; +}; // X2W_TEST_INPUT_LAYOUT: the stream also declares two per-vertex float3 elements, TEXCOORD in slot 0 and POSITION in // slot 1 at D3D12_APPEND_ALIGNED_ELEMENT, in the opposite order of the vertex shader's input signature // (startup_stream_fetch_check.py). @@ -42,10 +49,20 @@ struct LayoutStream { Layout layout; Stream stream; }; +struct RasterLayoutStream { + LayoutStream stream; + Raster rasterizer; +}; static const D3D12_INPUT_ELEMENT_DESC layout_elements[] = { {"TEXCOORD", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 1, D3D12_APPEND_ALIGNED_ELEMENT, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, }; +// X2W_TEST_INPUT_LAYOUT=gradient: 12-byte records whose first dword is a mask and whose XY follows at +4 +// (startup_rect_gap_check.py). Both views name the same records, each with a 12-byte stride. +static const D3D12_INPUT_ELEMENT_DESC gradient_elements[] = { + {"TEXCOORD", 0, DXGI_FORMAT_R32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, + {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 1, 4, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, +}; namespace { void* stream_root = nullptr; @@ -200,16 +217,36 @@ int prepare_stream_pipeline(const char* vs_path, const char* ps_path, const char &stream_alternate_root))) return 7; } - wchar_t layout_mode[8] = L""; - GetEnvironmentVariableW(L"X2W_TEST_INPUT_LAYOUT", layout_mode, 8); + wchar_t layout_mode[16] = L""; + GetEnvironmentVariableW(L"X2W_TEST_INPUT_LAYOUT", layout_mode, 16); const bool empty_layout = std::wcscmp(layout_mode, L"empty") == 0; // declared layout with zero elements - LayoutStream with_layout{{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, {layout_elements, empty_layout ? 0u : 2u}}, + const bool gradient_layout = std::wcscmp(layout_mode, L"gradient") == 0; + LayoutStream with_layout{{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, + {gradient_layout ? gradient_elements : layout_elements, empty_layout ? 0u : 2u}}, {{D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, {ps.data(), ps.size()}}, {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root}, {D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, {vs.data(), vs.size()}}}}; const bool layout = GetEnvironmentVariableW(L"X2W_TEST_INPUT_LAYOUT", nullptr, 0) != 0; - void* first = layout ? static_cast(&with_layout) : static_cast(&with_layout.stream); - const SIZE_T whole = layout ? sizeof(with_layout) : sizeof(with_layout.stream); + // X2W_TEST_RASTERIZER=back|back-ccw|front: cull mode and front-face winding for the translated draw. + char rasterizer_mode[16]{}; + const bool cull = GetEnvironmentVariableA("X2W_TEST_RASTERIZER", rasterizer_mode, sizeof(rasterizer_mode)) != 0; + RasterLayoutStream with_rasterizer{}; + static_assert(offsetof(RasterLayoutStream, rasterizer.desc) == offsetof(RasterLayoutStream, stream) + sizeof(LayoutStream) + 4); + if (cull) { + std::memcpy(&with_rasterizer.stream, &with_layout, sizeof(with_layout)); + with_rasterizer.rasterizer.tag = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER; + D3D12_RASTERIZER_DESC& raster = with_rasterizer.rasterizer.desc; + raster.FillMode = D3D12_FILL_MODE_SOLID; + raster.CullMode = std::strcmp(rasterizer_mode, "front") == 0 ? D3D12_CULL_MODE_FRONT : D3D12_CULL_MODE_BACK; + raster.FrontCounterClockwise = std::strcmp(rasterizer_mode, "back-ccw") == 0 ? TRUE : FALSE; + raster.DepthClipEnable = TRUE; + } + void* first = cull ? static_cast(&with_rasterizer) + : layout ? static_cast(&with_layout) + : static_cast(&with_layout.stream); + const SIZE_T whole = cull ? sizeof(with_rasterizer) - sizeof(Raster) + sizeof(unsigned) + sizeof(D3D12_RASTERIZER_DESC) + : layout ? sizeof(with_layout) + : sizeof(with_layout.stream); auto submit = [&](SIZE_T bytes) { D3D12_PIPELINE_STATE_STREAM_DESC desc{bytes, first}; const auto hr = reinterpret_cast(slots[86])(device, &desc, __uuidof(ID3D12PipelineState), &pso); From 263604fc6cbf49d24004db9b40792654cfde65a3 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 19:14:48 +0000 Subject: [PATCH 14/44] startup: cover BVH triangle operands and box return mode - assert the origin, direction and inverse-direction operands of the translated call - ignore the triangle return mode bit for box nodes in the translator guard and helper - add the triangle check to the Linux CI fragment - correct the BVH experiment notes and link both notes from experiments.md --- docs/experiments.md | 3 +++ .../experiments/startup-gfx2hlsl-bvh-box32.md | 5 ++-- .../startup-gfx2hlsl-bvh-triangle.md | 14 ++++++---- .../startup_gfx2hlsl_bvh_triangle.txt | 1 + tests/startup_gfx2hlsl_bvh_check.py | 27 +++++++++++++++++-- tests/startup_gfx2hlsl_bvh_triangle_check.py | 13 ++++++++- tools/startup/gfx2hlsl.py | 16 +++++++---- 7 files changed, 64 insertions(+), 15 deletions(-) create mode 100644 tests/checks/python-linux/startup_gfx2hlsl_bvh_triangle.txt diff --git a/docs/experiments.md b/docs/experiments.md index f25d09ff7f..4833e82240 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -4800,6 +4800,9 @@ Native readback remains pending, including the raw miss and disabled-slot words. The probe leaves translator behavior and form coverage unchanged. The node model and its witness set are described in [bvh-node-model.md](experiments/bvh-node-model.md). +The translator slices that consume the model are the +[FP32 and binary16 box nodes](experiments/startup-gfx2hlsl-bvh-box32.md) and the +[triangle nodes](experiments/startup-gfx2hlsl-bvh-triangle.md). ### gfx1013 2D explicit-LOD image gathers diff --git a/docs/experiments/startup-gfx2hlsl-bvh-box32.md b/docs/experiments/startup-gfx2hlsl-bvh-box32.md index 21acc67961..967256e65d 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-box32.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-box32.md @@ -29,7 +29,8 @@ in `min.x`. for binary16, two for FP32; `size=0` is a one-unit span) and below 4 GiB; - a constant node pointer whose low three bits are 4 (64-byte aligned) or 5 (128-byte aligned) and inside the same 4 GiB relative address window; the entire node must fit within the 48-bit absolute address space; -- either value of the sort bit. +- either value of the sort bit, and either value of the triangle return mode bit (bit 120); + it selects the triangle result layout and does not change a box result. The manifest names the node allocation with `srv bvh base 0x size 0x`, using the decoded byte address for `base` and the unchanged descriptor size field for `size`. All four original descriptor @@ -40,7 +41,7 @@ of this change. ## Refused by name -Triangle nodes (kinds 0..3), every other node kind, `image_bvh64_intersect_ray`, A16, +Every node kind other than 4 and 5, `image_bvh64_intersect_ray`, A16, non-sequential addresses, a pixel or vertex stage, a node pointer that is not a straight-line constant, a T# loaded at run time, a type other than 8, nonzero box growing, an absolute (zero) base, a size that does not cover the node, size bits above 4 GiB, a node address that wraps the 48-bit address space, diff --git a/docs/experiments/startup-gfx2hlsl-bvh-triangle.md b/docs/experiments/startup-gfx2hlsl-bvh-triangle.md index 5eeb202be9..73e87d9eec 100644 --- a/docs/experiments/startup-gfx2hlsl-bvh-triangle.md +++ b/docs/experiments/startup-gfx2hlsl-bvh-triangle.md @@ -26,8 +26,10 @@ barycentric numerators `u`, `v` and `w`, the determinant `u + (v + w)` and ## Return and descriptor Triangle return mode 1 (bit 120 of the BVH T#, bit 24 of descriptor DWORD 3) returns the four words -`{t, determinant, v, w}` as float bit patterns. A miss is `{+inf, 1.0, 0, 0}`. Return mode 0 and -every other reserved word-3 bit are refused by name before any HLSL is emitted. +`{t, determinant, v, w}` as float bit patterns. A miss is `{+inf, 1.0, 0, 0}`. For triangle nodes, +return mode 0 and every other reserved word-3 bit are refused by name before any HLSL is emitted. +Box nodes (kinds 4 and 5) ignore bit 24 because one T# can cover both node types; every other +word-3 bit is still refused for them. The accepted slice uses: @@ -60,9 +62,11 @@ python3 -B tests/startup_gfx2hlsl_bvh_triangle_check.py dispatch > 3) | 4, word0=0x1000, word1=0, word2=0x40, extent=extent, origin=origin, direction=direction, expected=expected)) + # A T# can cover both box and triangle nodes; box kinds ignore the triangle return mode + # bit. These cases fail if either the translator or the emitted box helper rejects it. + name, offset, extent, origin, direction, expected = RAYS[0] + cases.append(dict(name="box32_return_mode_ignored", helper="x2w_bvh_intersect_box32", + pointer=(offset >> 3) | 5, word0=0x1000, word1=SORT_ENABLE, word2=0x0b, + word3=RESOURCE_TYPE | 0x01000000, extent=extent, origin=origin, + direction=direction, expected=expected)) + name, offset, extent, origin, direction, expected = HALF_RAYS[0] + cases.append(dict(name="box16_return_mode_ignored", helper="x2w_bvh_intersect_box16", + pointer=(offset >> 3) | 4, word0=0x1000, word1=SORT_ENABLE, word2=0x40, + word3=RESOURCE_TYPE | 0x01000000, extent=extent, origin=origin, + direction=direction, expected=expected)) return cases -BUFFER_SIZE = RESULT_OFFSET + 16 * (len(RAYS) + len(UNSORTED_RAYS) + len(HALF_RAYS) + len(HALF_UNSORTED_RAYS)) +BUFFER_SIZE = RESULT_OFFSET + 16 * len(dispatch_cases()) def translate_program(*, node=0x05, sort_boxes=True, word0=0x1000, word1=None, word2=0x0b, @@ -348,6 +360,16 @@ def controls(): check("sort-disabled box16 call uses a zero sort word", "0x00001000u, 0x00000000u, 0x0000000bu, 0x80000000u" in call, call) + # One T# can cover both node types, so a box node ignores the triangle return mode bit. + for node, helper in ((0x05, "x2w_bvh_intersect_box32"), (0x04, "x2w_bvh_intersect_box16")): + pipe, hlsl, refusals = translate_program(node=node, word3=RESOURCE_TYPE | 0x01000000) + check("box kind %d with triangle return mode bit translates" % (node & 7), + pipe is not None and not refusals, str(refusals)) + if pipe is not None: + call = next((line for line in hlsl.splitlines() if helper + "(r0" in line), "") + check("box kind %d call preserves the ignored return mode bit" % (node & 7), + "0x00001000u, 0x80000000u, 0x0000000bu, 0x81000000u" in call, call) + # Independently decode the 40-bit unit field; test the same raw DWORDs in # the emitted call and the decoded byte-address binding in the manifest. for units, high, base in ((0x1000, 0, 0x100000), (0x1008, 0, 0x100800), @@ -549,9 +571,10 @@ def dispatch_hlsl(mutation=None): for case, item in enumerate(dispatch_cases()): inv = tuple(1.0 / c for c in item["direction"]) lines.append( - " uint4 r%d = %s(data, 0x%08xu, 0x%08xu, 0x%08xu, 0x%08xu, 0x80000000u, " + " uint4 r%d = %s(data, 0x%08xu, 0x%08xu, 0x%08xu, 0x%08xu, 0x%08xu, " "%s, float3(%s, %s, %s), float3(%s, %s, %s));" % ( case, item["helper"], item["pointer"], item["word0"], item["word1"], item["word2"], + item.get("word3", 0x80000000), ffloat(item["extent"]), ffloat(item["origin"][0]), ffloat(item["origin"][1]), ffloat(item["origin"][2]), ffloat(inv[0]), ffloat(inv[1]), ffloat(inv[2]))) for word in range(4): diff --git a/tests/startup_gfx2hlsl_bvh_triangle_check.py b/tests/startup_gfx2hlsl_bvh_triangle_check.py index f2748c502b..792e61fcb5 100644 --- a/tests/startup_gfx2hlsl_bvh_triangle_check.py +++ b/tests/startup_gfx2hlsl_bvh_triangle_check.py @@ -75,6 +75,9 @@ def controls(): check("triangle kind %d call carries the node and four results" % kind, "0x0000000%du" % kind in call_line and all("v%d = bt" % reg in hlsl for reg in range(32, 36)), call_line) + check("triangle kind %d call passes origin, direction and inverse from v18..v26" % kind, + "float3(F(v18), F(v19), F(v20)), float3(F(v21), F(v22), F(v23)), " + "float3(F(v24), F(v25), F(v26))" in call_line, call_line) pipe, hlsl, refusals = translate_triangle(0x00, sort_boxes=False) check("sort-disabled triangle translates", pipe is not None and not refusals, str(refusals)) @@ -83,6 +86,14 @@ def controls(): check("sort-disabled triangle call keeps the zero sort word", "0x00001000u, 0x00000000u, 0x0000000bu, 0x81000000u" in call, call) + # One T# can cover both node types, so a box node ignores the triangle return mode bit. + pipe, hlsl, refusals = translate_triangle(node=0x05, word3=RESOURCE_TYPE | TRIANGLE_MODE) + check("box node with triangle return mode bit translates", pipe is not None and not refusals, str(refusals)) + if pipe is not None: + call = next((line for line in hlsl.splitlines() if "x2w_bvh_intersect_box32(r0" in line), "") + check("box call preserves the ignored return mode bit", + "0x00001000u, 0x80000000u, 0x0000000bu, 0x81000000u" in call, call) + helpers = "\n".join(G.BVH_HELPERS) check("translated triangle shader embeds the dispatch-tested helpers", hlsl is not None and helpers in hlsl, "") @@ -102,7 +113,7 @@ def controls(): cases = [ ("triangle return mode 0", dict(node=0x00, word3=RESOURCE_TYPE), "does not match node kind 0"), - ("box return mode 1", dict(node=0x05, word3=RESOURCE_TYPE | TRIANGLE_MODE), "does not match node kind 5"), + ("box reserved word 3 bit", dict(node=0x05, word3=RESOURCE_TYPE | 0x100), "does not match node kind 5"), ("unknown node kind", dict(node=0x06), "node kind 6"), ("node outside size", dict(node=0x20, word2=3), "outside descriptor size"), ("absolute base", dict(node=0x00, word0=0, word1=0), "absolute node base"), diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index c59f66dd0f..33923008bc 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -8108,8 +8108,13 @@ def op_image_bvh_intersect_ray(self, ops, mods): if vals[3] is not None: if (vals[3] >> 28) & 0xf != 8: raise Unsupported('%s descriptor type %d is not 8' % (name, (vals[3] >> 28) & 0xf)) - expected_mode = 0x01000000 if triangle else 0 - if (vals[3] & 0x0fffffff) != expected_mode: + # The triangle return mode bit only selects the triangle result layout. One T# can + # cover both node types, so a box node ignores it; every other reserved bit is refused. + if triangle: + mode_ok = (vals[3] & 0x0fffffff) == 0x01000000 + else: + mode_ok = (vals[3] & 0x0effffff) == 0 + if not mode_ok: raise Unsupported('%s descriptor word 3 %#x does not match node kind %d' % (name, vals[3], kind)) base = key[0][1] if base == 0: @@ -11106,7 +11111,7 @@ def read(fmt, data, offset): # slice does not bind, so it is refused here as a miss rather than read at address zero. 'bool x2w_bvh_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', ' return (word1 & 0x7fffff00u) == 0u &&', - ' word3 == 0x80000000u && word2 < 0x04000000u &&', + ' (word3 & 0xfeffffffu) == 0x80000000u && word2 < 0x04000000u &&', ' (word0 != 0u || (word1 & 0x000000ffu) != 0u);', '}', # A triangle node is 64 bytes: five float3 vertices at 0..59 and one ID dword at 60. @@ -11134,8 +11139,9 @@ def read(fmt, data, offset): ' float rz = x2w_bvh_component(rel, kz);', ' return float3(rx - sx * rz, ry - sy * rz, sz * rz);', '}', - # Triangle return mode 1 (bit 120) is the only triangle mode this slice lowers. The box - # return mode is zero and is checked separately by each box helper. + # Triangle return mode 1 (bit 120) is the only triangle mode this slice lowers. A box + # node ignores bit 120 because one T# covers both node types; its helper checks every + # other word-3 bit. 'bool x2w_bvh_triangle_descriptor_ok(uint word0, uint word1, uint word2, uint word3) {', ' return (word1 & 0x7fffff00u) == 0u && (word3 & 0x0fffffffu) == 0x01000000u &&', ' (word3 >> 28u) == 8u && word2 < 0x04000000u &&', From 9360bcaef424cf8a8bf8c0e495af4c057ce61dae Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 19:14:51 +0000 Subject: [PATCH 15/44] runtime: bind from the recovered translation after PSO fallback pipeline_for may replace the native candidate with the published disk translation. Create the PSO before preparing the D16, formatted-buffer and fixed-vertex bindings so they come from the final translation, and recompute indexed-rectangle geometry when the fallback changes the fixed stream. Add the RTV variant fallback and invalid pixel-blob cases. --- src/startup_stubs/d3d12_draw.inl | 54 ++++++++++++------- tests/startup_native_graphics_draw_check.py | 58 +++++++++++++++++++++ 2 files changed, 92 insertions(+), 20 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 4f9c12d5a3..745a94a5c2 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2560,20 +2560,47 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI BoundPipeline* bound = translation_for(pass.pipeline); Translation* tr = bound ? translation_for_targets(bound->translation, pass) : nullptr; if (indirect && tr) indirect->shader_key = tr->key; + if (!tr || tr->state != 1) { + if (indirect) indirect->refusal_code = indirect_refusal_code::translation_not_ready; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } + // pipeline_for may replace the native candidate with the published disk translation. + // Create the PSO first, then derive every binding from the translation it leaves in tr. + bool fixed_stream = !tr->fixed_stream.empty(); + bool geometry_rect = indexed_rect || (rect && fixed_stream); + ID3D12PipelineState* pipeline = ensure_draw_heap(self->own().list_device) ? pipeline_for(*bound, *tr, pass, geometry_rect) : nullptr; + if (pipeline) { + const bool recovered_fixed_stream = !tr->fixed_stream.empty(); + const bool recovered_geometry_rect = indexed_rect || (rect && recovered_fixed_stream); + if (recovered_geometry_rect != geometry_rect) { + pipeline = pipeline_for(*bound, *tr, pass, recovered_geometry_rect); + geometry_rect = recovered_geometry_rect; + } + fixed_stream = recovered_fixed_stream; + } + if (indirect && indexed_rect && !pipeline) { + indirect->set_refusal("translated indexed rectangle geometry unavailable", + indirect_refusal_code::indexed_rect_unavailable); + } + if (!pipeline || (tr->samplers.heap && !prepare_draw_sampler_heap(pass, list, tr->samplers.reserved_fallback))) { + if (indirect && !(indexed_rect && !pipeline)) + indirect->refusal_code = !pipeline ? indirect_refusal_code::pipeline_unavailable + : indirect_refusal_code::sampler_heap_unavailable; + ReleaseSRWLockExclusive(&draw_lock); + return false; + } std::uint32_t d16_unorm16[32] = {}; FormattedBufferDescriptor formatted_buffers[32] = {}; - const bool translation_ok = tr && tr->state == 1; - const bool d16_ok = translation_ok && d16_srvs_ready(*tr, pass, d16_unorm16); + const bool d16_ok = d16_srvs_ready(*tr, pass, d16_unorm16); const bool formatted_ok = d16_ok && formatted_buffers_ready(*tr, pass, formatted_buffers); if (!formatted_ok) { - if (indirect && tr) - indirect->refusal_code = !translation_ok ? indirect_refusal_code::translation_not_ready - : !d16_ok ? indirect_refusal_code::d16_srv_not_ready - : indirect_refusal_code::formatted_buffer_not_ready; + if (indirect) + indirect->refusal_code = !d16_ok ? indirect_refusal_code::d16_srv_not_ready + : indirect_refusal_code::formatted_buffer_not_ready; ReleaseSRWLockExclusive(&draw_lock); return false; } - const bool fixed_stream = !tr->fixed_stream.empty(); D3D12_VERTEX_BUFFER_VIEW fixed_view{}; ID3D12Resource* fixed_resource = nullptr; if (fixed_stream && (indirect || !fixed_vertex_view(self, pass, *tr, indexed, start, count, fixed_view, fixed_resource))) { @@ -2636,19 +2663,6 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI return false; } } - const bool geometry_rect = indexed_rect || (rect && fixed_stream); - ID3D12PipelineState* pipeline = ensure_draw_heap(self->own().list_device) ? pipeline_for(*bound, *tr, pass, geometry_rect) : nullptr; - if (indirect && indexed_rect && !pipeline) { - indirect->set_refusal("translated indexed rectangle geometry unavailable", - indirect_refusal_code::indexed_rect_unavailable); - } - if (!pipeline || (tr->samplers.heap && !prepare_draw_sampler_heap(pass, list, tr->samplers.reserved_fallback))) { - if (indirect && !(indexed_rect && !pipeline)) - indirect->refusal_code = !pipeline ? indirect_refusal_code::pipeline_unavailable - : indirect_refusal_code::sampler_heap_unavailable; - ReleaseSRWLockExclusive(&draw_lock); - return false; - } PixelUavBinding uav_bindings[pixel_uav_limit]; if (!resolve_pixel_uavs(*tr, pass, uav_bindings)) { ReleaseSRWLockExclusive(&draw_lock); diff --git a/tests/startup_native_graphics_draw_check.py b/tests/startup_native_graphics_draw_check.py index 51cde53e9d..f51f7b268d 100644 --- a/tests/startup_native_graphics_draw_check.py +++ b/tests/startup_native_graphics_draw_check.py @@ -93,6 +93,45 @@ def check(folder, consumer, sdk, adapter, compiler): for path, expected in published.items()) print(f"{adapter} PSO: candidate failure recovered the published disk pair, 16 red and 16 clear pixels") + # An RTV variant is a separate published pair. Draw it natively first so the runtime + # publishes req_.rtv, compile that request, then inject the candidate PSO failure. + variant_args = args + ["2"] # DXGI_FORMAT_R32G32B32A32_FLOAT + variant_red = bytes.fromhex("0000803f00000000000000000000803f") + variant_clear = bytes.fromhex("00000000000000000000803f0000803f") + pixels.unlink() + run = subprocess.run(variant_args, env=env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0 and "-> drawn;" in run.stderr, run.stderr[-8000:] + assert "no RTV translation" not in run.stderr, run.stderr[-8000:] + assert pixels.read_bytes() == variant_red, pixels.read_bytes().hex() + variant_request, = cache.glob("req_*.rtv") + variant_key = variant_request.stem.removeprefix("req_") + subprocess.run([compiler, "--watch", sdk, cache, cache, "--once"], check=True, timeout=45) + variant_manifest = cache / (variant_key + ".txt") + variant_published = {p: (p.read_bytes(), p.stat().st_mtime_ns) for p in + (variant_manifest, variant_manifest.with_suffix(".vs.cso"), + variant_manifest.with_suffix(".ps.cso"))} + pixels.unlink() + run = subprocess.run(variant_args, env=pso_env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0, run.stderr + assert "candidate pipeline failed 0x80004005 (injected)" in run.stderr, run.stderr[-8000:] + assert "published disk pair recovered" in run.stderr and "-> drawn;" in run.stderr, run.stderr[-8000:] + assert pixels.read_bytes() == variant_red, pixels.read_bytes().hex() + assert all(path.read_bytes() == expected[0] and path.stat().st_mtime_ns == expected[1] + for path, expected in variant_published.items()) + held_variant = Path(str(variant_manifest) + ".hold") + variant_manifest.rename(held_variant) + try: + pixels.unlink() + run = subprocess.run(variant_args, env=pso_env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0, run.stderr + assert "no valid published disk pair" in run.stderr and "-> drawn;" not in run.stderr, run.stderr[-8000:] + assert pixels.read_bytes() == variant_clear, pixels.read_bytes().hex() + assert all(path.read_bytes() == expected[0] and path.stat().st_mtime_ns == expected[1] + for path, expected in variant_published.items() if path != variant_manifest) + print(f"{adapter} RTV variant: candidate failure recovered the disk variant; a missing manifest refused") + finally: + held_variant.rename(variant_manifest) + # The native path still creates its own pipeline when no fault is injected. pixels.unlink() run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45) @@ -133,6 +172,25 @@ def check(folder, consumer, sdk, adapter, compiler): held_manifest.rename(manifest) assert all(path.read_bytes() == expected[0] and path.stat().st_mtime_ns == expected[1] for path, expected in published.items()) + + # The manifest and vertex blob stay valid, but the pixel blob no longer creates a PSO. + held_ps = Path(str(ps_cso) + ".hold") + ps_cso.rename(held_ps) + invalid_ps = b"not a DXIL container" + ps_cso.write_bytes(invalid_ps) + invalid_mtime = ps_cso.stat().st_mtime_ns + try: + pixels.unlink() + run = subprocess.run(args, env=pso_env, capture_output=True, text=True, timeout=45) + assert run.returncode == 0, run.stderr + assert "published disk pair pipeline failed" in run.stderr, run.stderr[-8000:] + assert "-> drawn;" not in run.stderr, run.stderr[-8000:] + assert pixels.read_bytes() == clear * 32, pixels.read_bytes().hex() + assert ps_cso.read_bytes() == invalid_ps and ps_cso.stat().st_mtime_ns == invalid_mtime + print(f"{adapter} invalid PS blob: disk PSO refused, 32 clear pixels, file unchanged") + finally: + ps_cso.unlink() + held_ps.rename(ps_cso) ps.write_bytes(patched_pixel(1, [0xffffffff], export=(0xf800180f, 0x01000001))) run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=45) assert run.returncode == 0 and "refused:" in run.stderr and "-> drawn;" not in run.stderr, run.stderr From 1600accb50df76e8692553116917a368568a2754 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 20:22:10 +0000 Subject: [PATCH 16/44] runtime: add opt-in input trace for the virtual gamepad --- docs/experiments/startup-input-trace.md | 102 +++++++ docs/startup-runtime.md | 26 ++ src/startup_stubs/gameinput.cpp | 80 ++++++ tests/cmake/startup_gameinput_trace.cmake | 8 + tests/startup_gameinput_trace.cpp | 311 ++++++++++++++++++++++ 5 files changed, 527 insertions(+) create mode 100644 docs/experiments/startup-input-trace.md create mode 100644 tests/cmake/startup_gameinput_trace.cmake create mode 100644 tests/startup_gameinput_trace.cpp diff --git a/docs/experiments/startup-input-trace.md b/docs/experiments/startup-input-trace.md new file mode 100644 index 0000000000..2984ed251c --- /dev/null +++ b/docs/experiments/startup-input-trace.md @@ -0,0 +1,102 @@ +# Startup input trace + +`X2W_INPUT_TRACE=1` makes the `GameInput.dll` stand-in log the gamepad state it resolves for each +`IGameInput::GetCurrentReading` call. The state is read after the keyboard, XInput pad 0, the +`Local\x2w_input_pad` shared block, `X2W_INPUT_PRESS` and `X2W_INPUT_SCRIPT` have been merged, so the +trace shows the values the runtime returns to the title. It is a diagnostic for checking that a +scripted stick, trigger or button reaches the runtime when the corresponding picture is presented. +The switch is off by default and adds no line without it. + +## Checking it + +Build the source-built fixture and run its CTest: + +```powershell +cmake --build --preset dev --target startup_gameinput_trace +ctest --preset dev --no-tests=error -R '^startup_gameinput_trace$' -V +``` + +For a normal startup run, set the switch next to the script: + +```powershell +$env:X2W_INPUT_SCRIPT = 'wait,mark=screen@+0,lx=1@+0.5+2,4@+2.5' +$env:X2W_INPUT_TRACE = '1' +.\tools\startup\run.ps1 ... +``` + +The trace goes to stderr and to the file named by `X2W_TRAP_LOG`, like the stand-in's other lines. + +## Line format + +Every line starts with `x2w-input-trace`. A state line is written when the resolved gamepad state +changes and, while it is unchanged, at most once every 250 ms: + +```text +x2w-input-trace state buttons=0x00000004 lt=0.000 rt=0.000 lx=1.000 ly=0.500 rx=0.000 ry=0.000 script=2.500 present=11 +``` + +`buttons` is the GameInput button mask in hexadecimal. `lt`, `rt`, `lx`, `ly`, `rx` and `ry` use +the units of `GamepadState` (triggers in [0, 1], sticks in [-1, 1]). `script` is the current time on +the script's time base in seconds, or `off` when no timed entry or wait/mark is active. `present` +is the latest present number published by the picture signature, or `none` when no presenter +sample is available. The state line does not depend on the title having called +`GetGamepadState`; it is sampled when the stand-in captures a reading. + +Script marks and waits add one event line each: + +```text +x2w-input-trace wait event=begun item=2 at=0.000 elapsed=0.000 signal=1 +x2w-input-trace wait event=changed item=2 at=1.000 elapsed=1.000 signal=1 +x2w-input-trace wait event=done item=2 at=1.500 elapsed=1.500 signal=1 +x2w-input-trace wait event=timeout item=4 at=2.000 elapsed=2.000 signal=0 stopped=0 group=- +x2w-input-trace mark label=turn item=5 at=2.500 present=11 +x2w-input-trace group label=list items=2-6 failed_item=4 at=3.000 +``` + +`item` is the 1-based script item, and `at` is on the same shifted script time base as the state +lines. A wait that times out names its group, or `-` when it has none. A mark without a presenter +prints `present=none`. + +## Volume + +The trace logs one state line per change and one periodic line per 250 ms of unchanged state, so a +steady run produces at most four state lines per second. Wait, mark and group lines occur once per +script event, and the parser limits a script to 256 timed items, so the event volume follows the +script. Without `X2W_INPUT_TRACE=1`, the stand-in reads no clock for the trace and writes no +`x2w-input-trace` line. + +## What it verifies for movement + +The `script` and `present` fields on one line tie an input value to the picture being presented. For +a movement question, this distinguishes an input that never reached the runtime from one that was +present but produced no visible movement. It also exposes axis signs and trigger ranges before they +are consumed: `lx=1.000` is right, `ly=1.000` is up, and a trigger outside [0, 1] would be a runtime +mapping problem rather than a rendering problem. Marks name the frame where a movement starts, and +waits show how long the script blocked before the movement was allowed to run. + +The trace covers the GameInput stand-in only. It does not prove that the title read the reading, +that the reading was used by a particular title system, or that a draw or present changed. Pair it +with the stand-in's `x2w-input gamepad buttons ... read by the title` line, a present/capture log, +or a title-side movement observation for that evidence. + +## Fixture + +`startup_gameinput_trace` runs one synthetic script in a child process with the switch on and again +with it off. The child sets `X2W_INPUT_CLOCK_MS` before every poll and publishes a new picture at +1.0 s. The script is: + +```text +mark=start@0,wait=0.5/2,4@+0.5+0.5,lx=1@+0.5+1,mark=turn@+0,ly=0.5@+0+0.5 +``` + +The wait completes at 1.5 s, so A is down at 2.0-2.5 s and the left stick is right with Y at 0.5 at +2.5-3.0 s. The trace child must contain the exact state lines at 2.000 s and 2.500 s, the begun, +changed and done wait lines, both marks, no timeout, and between 12 and 20 state lines over the four +second run. The control must observe the same gamepad states, keep the ordinary `x2w-input script` +mark line, and contain no `x2w-input-trace` line. The expected states and trace lines are built from +source; the fixture uses no game files, dump or captured input. + +On the local Windows x64 Debug build (MSVC 19.44, CMake/Ninja), `startup_gameinput_trace` passed +with both modes. The same build ran `startup_gameinput_script_long`, +`startup_gameinput_script_entries` and `startup_gameinput_script_syntax` successfully, and the +stand-in's keys, history and contract checks still passed without the switch. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 976eb0a8a2..7c502232dc 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1581,6 +1581,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_DEVICE_TYPE=` | with `X2W_RUNTIME_PROXY=1`, answers the title's reads of the OEM `ConsoleMode` registry value: `6` = 0x60 (Series S), `7` = 0x64 (Series X), `1` = value missing (PC); unset, the real registry answers. See [Console profile](#console-profile) | | `X2W_STORAGE_PATH`, `X2W_STORAGE_MB`, `X2W_TITLE_ID` | persistent local storage and the manifest values the runtime would return. The path is the root of the drive the title sees, not its save folder: the title appends `x2w-gamesave` itself. It is UTF-8, with a trailing separator added when missing. If the path is invalid or exceeds 259 bytes including the separator, the proxy logs the refusal and uses `S:\` (`src/startup_stubs/storage_root_utf8.h`, `ctest --preset release --no-tests=error -R '^startup_storage_root'`). | | `X2W_INPUT_SCRIPT=mask@sec,...` | timed virtual gamepad presses, holds, stick or trigger values and waits for the presented picture: see [Input script](#input-script); keyboard and XInput pad 0 also work. Up to 256 entries and 4,095 characters; a longer value is ignored and logged, and dropped or malformed entries are logged (`ctest --preset dev --no-tests=error -R '^startup_gameinput_script_(long|entries|syntax)$'`) | +| `X2W_INPUT_TRACE=1` | opt-in: logs the resolved virtual gamepad state (buttons and all six axes), the script time or `off`, the present number or `none`, and one line per script wait, mark or skipped group, all prefixed `x2w-input-trace`. At most one state line per change and one per 250 ms while unchanged; unset, nothing is logged. See [Input trace](#input-trace). | | `X2W_SAMPLER_HEAP=1` | `gfx2hlsl.py` translates a sampler-heap load with a run-time offset into `SamplerState qh[2048] : register(s0, space1)` and writes `smpheap 2048 1 fallback 2047`. The stand-in uses entries 0 to 2046 for the bound heap and reserves entry 2047 for unaligned or out-of-range offsets. It also accepts the original `smpheap 2048 1` manifest with all 2,048 entries available. [#1143](https://github.com/R0Y00/Xbox2Windows/issues/1143) | | `X2W_XG_VERBOSE=1` | logs every texture layout query with its mip sizes | | `X2W_XG_BC7_4K_S_LAYOUT=1` | enables the BC7 tiled layout, copy and draw upload when `X2W_D3D12_PERMISSIVE=1` | @@ -1976,6 +1977,31 @@ ctest --preset dev --no-tests=error -R '^startup_gameinput_script_(long|entries| It exits 77 (skip) after the parser checks when XInput pad 0 is connected, because that pad's values merge into every reading. +### Input trace + +`X2W_INPUT_TRACE=1` (off by default) logs the gamepad state the stand-in resolves after the +keyboard, XInput pad 0, the shared pad block, `X2W_INPUT_PRESS` and `X2W_INPUT_SCRIPT` have been +merged. Every line starts with `x2w-input-trace` and goes to stderr and `X2W_TRAP_LOG` like the +stand-in's other lines. A state line has the form + +```text +x2w-input-trace state buttons=0x00000004 lt=0.000 rt=0.000 lx=1.000 ly=0.500 rx=0.000 ry=0.000 script=2.500 present=11 +``` + +where `script` is the script time in seconds or `off`, and `present` is the latest present number +from the picture signature or `none` without a presenter sample. One state line is written per +change and, while the state is unchanged, at most once every 250 ms. Waits, marks and skipped +groups add one `x2w-input-trace wait`, `mark` or `group` line each, with the script item and shifted +script time. The fixture `startup_gameinput_trace` runs one script with the switch on and off: + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gameinput_trace$' -V +``` + +The control must observe the same gamepad states and write no trace line. See +[the input trace experiment](experiments/startup-input-trace.md) for the exact line fields, the +fixture's expected states and the movement evidence it supports. + `IGameInput::GetTemporalReading` uses the v0 ABI and returns `E_NOTIMPL` as [documented by Microsoft](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/input/gameinput/deprecated/interfaces/igameinput/methods/igameinput_gettemporalreading). The `startup_gameinput_contracts_check` fixture covers the refusal. diff --git a/src/startup_stubs/gameinput.cpp b/src/startup_stubs/gameinput.cpp index b135633eca..e080d8eada 100644 --- a/src/startup_stubs/gameinput.cpp +++ b/src/startup_stubs/gameinput.cpp @@ -221,8 +221,79 @@ bool read_signal(x2w_input_script::Signal& out) return true; } +// X2W_INPUT_TRACE=1: one "x2w-input-trace" line per resolved gamepad state change, plus at most one +// every 250 ms while the state stays the same. The resolved state is what capture_current() records, +// after keyboard, XInput, the shared block, X2W_INPUT_PRESS and the script have been merged. +bool trace_enabled() +{ + static const bool on = x2w_local::env_on("X2W_INPUT_TRACE"); + return on; +} + +void trace_state(const GamepadState& state, bool scripted, double script_time, bool present, std::uint64_t present_number) +{ + constexpr u64 interval_ms = 250; + static SRWLOCK trace_lock = SRWLOCK_INIT; + static GamepadState last{}; + static bool have_last = false; + static u64 last_ms = 0; + const u64 now = process_milliseconds(); + bool log = false; + AcquireSRWLockExclusive(&trace_lock); + if (!have_last || std::memcmp(&state, &last, sizeof(state)) != 0 || now < last_ms || now - last_ms >= interval_ms) { + log = true; + last = state; + have_last = true; + last_ms = now; + } + ReleaseSRWLockExclusive(&trace_lock); + if (!log) return; + char script[24], present_text[24]; + if (scripted) + std::snprintf(script, sizeof(script), "%.3f", script_time); + else + std::snprintf(script, sizeof(script), "off"); + if (present) + std::snprintf(present_text, sizeof(present_text), "%llu", static_cast(present_number)); + else + std::snprintf(present_text, sizeof(present_text), "none"); + x2w_local::logf("x2w-input-trace state buttons=0x%08x lt=%.3f rt=%.3f lx=%.3f ly=%.3f rx=%.3f ry=%.3f script=%s present=%s", + static_cast(state.buttons), state.left_trigger, state.right_trigger, state.left_x, state.left_y, + state.right_x, state.right_y, script, present_text); +} + +void trace_event(const x2w_input_script::Event& e) +{ + using x2w_input_script::Event; + switch (e.type) { + case Event::wait_begun: + case Event::wait_changed: + case Event::wait_done: + x2w_local::logf("x2w-input-trace wait event=%s item=%zu at=%.3f elapsed=%.3f signal=%d", + e.type == Event::wait_begun ? "begun" : e.type == Event::wait_changed ? "changed" : "done", e.item, e.at, + e.elapsed, e.signal ? 1 : 0); + break; + case Event::wait_timeout: + x2w_local::logf("x2w-input-trace wait event=timeout item=%zu at=%.3f elapsed=%.3f signal=%d stopped=%d group=%s", + e.item, e.at, e.elapsed, e.signal ? 1 : 0, e.stopped ? 1 : 0, e.label.empty() ? "-" : e.label.c_str()); + break; + case Event::mark: + if (e.signal) + x2w_local::logf("x2w-input-trace mark label=%s item=%zu at=%.3f present=%llu", e.label.c_str(), e.item, e.at, + static_cast(e.present)); + else + x2w_local::logf("x2w-input-trace mark label=%s item=%zu at=%.3f present=none", e.label.c_str(), e.item, e.at); + break; + case Event::group_skipped: + x2w_local::logf("x2w-input-trace group label=%s items=%zu-%zu failed_item=%zu at=%.3f", e.label.c_str(), e.group_item, + e.end_item, e.item, e.at); + break; + } +} + void log_event(const x2w_input_script::Event& e) { + if (trace_enabled()) trace_event(e); using x2w_input_script::Event; switch (e.type) { case Event::wait_begun: @@ -339,8 +410,12 @@ GamepadState sample() // Waits and marks (wait=..., mark=..., @+) go through the timeline; other scripts as before. const x2w_input_script::Script& script = input_script(); const bool timeline = !script.waits.empty() || !script.marks.empty(); + bool scripted = false; + double script_time = 0; if (!script.entries.empty() || timeline) { const double t = script_seconds(script); + scripted = true; + script_time = t; double end = -1; const x2w_input_script::Output out = timeline ? play_timeline(script, t, end) : x2w_input_script::play(script, t); s.buttons |= out.buttons; @@ -354,6 +429,11 @@ GamepadState sample() x2w_local::logf("x2w-input script time passed its last entry (%zu entries, ended at %.3f s on the script time base)", script.entries.size(), end); } + if (trace_enabled()) { + x2w_input_script::Signal signal; + const bool present = read_signal(signal); + trace_state(s, scripted, script_time, present, present ? signal.present : 0); + } return s; } diff --git a/tests/cmake/startup_gameinput_trace.cmake b/tests/cmake/startup_gameinput_trace.cmake new file mode 100644 index 0000000000..9b89f4e0f6 --- /dev/null +++ b/tests/cmake/startup_gameinput_trace.cmake @@ -0,0 +1,8 @@ +# X2W_INPUT_TRACE=1 logs the resolved gamepad state and the script's marks and waits. The test runs +# the same script with the switch on and off; the control must not produce an x2w-input-trace line. +add_executable(startup_gameinput_trace tests/startup_gameinput_trace.cpp) +target_include_directories(startup_gameinput_trace PRIVATE src) +target_compile_features(startup_gameinput_trace PRIVATE cxx_std_17) +add_dependencies(startup_gameinput_trace startup_stub_gameinput) +add_test(NAME startup_gameinput_trace COMMAND startup_gameinput_trace "$") +set_tests_properties(startup_gameinput_trace PROPERTIES RUN_SERIAL TRUE TIMEOUT 60 SKIP_RETURN_CODE 77) diff --git a/tests/startup_gameinput_trace.cpp b/tests/startup_gameinput_trace.cpp new file mode 100644 index 0000000000..bf9f8c8551 --- /dev/null +++ b/tests/startup_gameinput_trace.cpp @@ -0,0 +1,311 @@ +// Checks the opt-in GameInput input trace (X2W_INPUT_TRACE=1). A child process plays one +// X2W_INPUT_SCRIPT through IGameInput::GetCurrentReading with X2W_INPUT_CLOCK_MS; the parent runs +// the same child with the switch on and off, so the control proves that the default path logs no +// x2w-input-trace line and still observes the same gamepad states. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include "startup_stubs/present_signature.h" + +#include +#include +#include +#include + +namespace { + +constexpr std::uint32_t kind_gamepad = 0x00040000; +constexpr std::uint32_t button_a = 0x4; +constexpr const char* trace_prefix = "x2w-input-trace"; + +struct GamepadState { + std::uint32_t buttons; + float leftTrigger, rightTrigger, leftThumbstickX, leftThumbstickY, rightThumbstickX, rightThumbstickY; +}; +static_assert(sizeof(GamepadState) == 28, "GamepadState layout"); + +struct PadShared { + std::uint32_t magic, buttons, title_read, reads; +}; + +struct IGameInputReading { + const void* const* vtbl; + std::uint32_t Release() + { + using Fn = std::uint64_t(__stdcall*)(IGameInputReading*); + return static_cast(reinterpret_cast(vtbl[2])(this)); + } + bool GetGamepadState(GamepadState* state) + { + using Fn = bool(__stdcall*)(IGameInputReading*, GamepadState*); + return reinterpret_cast(vtbl[22])(this, state); + } +}; + +struct IGameInput { + const void* const* vtbl; + std::uint32_t Release() + { + using Fn = std::uint64_t(__stdcall*)(IGameInput*); + return static_cast(reinterpret_cast(vtbl[2])(this)); + } + HRESULT GetCurrentReading(std::uint32_t kind, void* device, IGameInputReading** reading) + { + using Fn = HRESULT(__stdcall*)(IGameInput*, std::uint32_t, void*, IGameInputReading**); + return reinterpret_cast(vtbl[4])(this, kind, device, reading); + } +}; + +int failures = 0; + +void check(bool ok, const char* what) +{ + if (ok) return; + ++failures; + std::printf("FAIL: %s\n", what); +} + +void clear_shared_pad() +{ + HANDLE mapping = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, sizeof(PadShared), L"Local\\x2w_input_pad"); + if (auto* shared = mapping ? static_cast(MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(PadShared))) : nullptr) + shared->buttons = 0; +} + +std::string read_log(const std::string& path) +{ + std::string text; + if (FILE* file = std::fopen(path.c_str(), "rb")) { + char buffer[4096]; + for (std::size_t n; (n = std::fread(buffer, 1, sizeof(buffer), file)) > 0;) text.append(buffer, n); + std::fclose(file); + } + return text; +} + +std::size_t count(const std::string& text, const char* needle) +{ + std::size_t found = 0; + for (std::size_t at = text.find(needle); at != std::string::npos; at = text.find(needle, at + 1)) ++found; + return found; +} + +bool same_state(const GamepadState& state, std::uint32_t buttons, float lt, float rt, float lx, float ly, float rx, float ry) +{ + return state.buttons == buttons && state.leftTrigger == lt && state.rightTrigger == rt && state.leftThumbstickX == lx && + state.leftThumbstickY == ly && state.rightThumbstickX == rx && state.rightThumbstickY == ry; +} + +bool expected_at(int ms, GamepadState& want) +{ + want = {}; + if (ms >= 2000 && ms < 2500) { + want.buttons = button_a; + } else if (ms >= 2500 && ms < 3000) { + want.leftThumbstickX = 1.0f; + want.leftThumbstickY = 0.5f; + } else if (ms >= 3000 && ms < 3500) { + want.leftThumbstickX = 1.0f; + } + return true; +} + +bool read_at(IGameInput* input, int ms, GamepadState& state) +{ + char text[24]; + std::snprintf(text, sizeof(text), "%d", ms); + SetEnvironmentVariableA("X2W_INPUT_CLOCK_MS", text); + IGameInputReading* reading = nullptr; + const HRESULT hr = input->GetCurrentReading(kind_gamepad, nullptr, &reading); + bool ok = SUCCEEDED(hr) && reading && reading->GetGamepadState(&state); + if (reading) reading->Release(); + return ok; +} + +bool xinput_pad_connected() +{ + struct State { + DWORD packet; + BYTE pad[12]; + }; + HMODULE module = LoadLibraryW(L"xinput1_4.dll"); + if (!module) return false; + using Fn = DWORD(WINAPI*)(DWORD, State*); + const auto get = reinterpret_cast(GetProcAddress(module, "XInputGetState")); + State state{}; + return get && get(0, &state) == 0; +} + +// The script starts with a mark and a wait, then presses A and moves the left stick. The wait +// completes 1.5 s after the child publishes a new picture at 1.0 s; the entries that follow are +// shifted to 2.0, 2.5, 3.0 and 3.5 s. +constexpr const char* script_text = + "mark=start@0,wait=0.5/2,4@+0.5+0.5,lx=1@+0.5+1,mark=turn@+0,ly=0.5@+0+0.5"; + +int run_child(const char* dll, bool trace) +{ + clear_shared_pad(); + SetEnvironmentVariableA("X2W_INPUT_PRESS", nullptr); + SetEnvironmentVariableA("X2W_INPUT_KEYS", nullptr); + + x2w_present_signature::Block* block = x2w_present_signature::create_block(GetCurrentProcessId(), 4); + if (!block) { + std::printf("child: create_block failed\n"); + return 2; + } + std::uint8_t first[x2w_present_signature::cells], second[x2w_present_signature::cells]; + std::memset(first, 40, sizeof(first)); + std::memset(second, 200, sizeof(second)); + x2w_present_signature::publish(block, first, 10); + x2w_present_signature::note_present(block, 10); + + HMODULE module = LoadLibraryA(dll); + if (!module) { + std::printf("child: LoadLibraryA(%s) failed: %lu\n", dll, GetLastError()); + return 2; + } + using CreateFn = HRESULT(__stdcall*)(IGameInput**); + const auto create = reinterpret_cast(GetProcAddress(module, "GameInputCreate")); + IGameInput* input = nullptr; + if (!create || FAILED(create(&input)) || !input) { + std::printf("child: GameInputCreate failed\n"); + FreeLibrary(module); + return 2; + } + + for (int ms = 0; ms <= 4000; ms += 50) { + if (ms == 1000) { + x2w_present_signature::publish(block, second, 11); + x2w_present_signature::note_present(block, 11); + } + GamepadState state{}; + if (!read_at(input, ms, state)) { + std::printf("child: GetCurrentReading failed at %d ms\n", ms); + ++failures; + break; + } + GamepadState want{}; + expected_at(ms, want); + if (!same_state(state, want.buttons, want.leftTrigger, want.rightTrigger, want.leftThumbstickX, want.leftThumbstickY, + want.rightThumbstickX, want.rightThumbstickY)) { + std::printf("child: %s at %d ms: buttons 0x%x lt %g rt %g lx %g ly %g rx %g ry %g\n", trace ? "trace" : "control", + ms, state.buttons, state.leftTrigger, state.rightTrigger, state.leftThumbstickX, state.leftThumbstickY, + state.rightThumbstickX, state.rightThumbstickY); + ++failures; + break; + } + } + input->Release(); + FreeLibrary(module); + + char log_path[MAX_PATH]{}; + const DWORD log_length = GetEnvironmentVariableA("X2W_TRAP_LOG", log_path, MAX_PATH); + if (!log_length || log_length >= MAX_PATH) { + std::printf("child: X2W_TRAP_LOG missing\n"); + return 2; + } + const std::string log = read_log(log_path); + if (trace) { + const char* const state_line = + "x2w-input-trace state buttons=0x00000004 lt=0.000 rt=0.000 lx=0.000 ly=0.000 rx=0.000 ry=0.000 " + "script=2.000 present=11"; + const char* const stick_line = + "x2w-input-trace state buttons=0x00000000 lt=0.000 rt=0.000 lx=1.000 ly=0.500 rx=0.000 ry=0.000 " + "script=2.500 present=11"; + check(count(log, state_line) == 1, "trace: A press line with script time 2.000 and present 11"); + check(count(log, stick_line) == 1, "trace: left stick and Y axis line at script time 2.500"); + check(count(log, "x2w-input-trace wait event=begun item=2 at=0.000 elapsed=0.000 signal=1") == 1, + "trace: wait begun line"); + check(count(log, "x2w-input-trace wait event=changed item=2 at=1.000 elapsed=1.000 signal=1") == 1, + "trace: wait changed line"); + check(count(log, "x2w-input-trace wait event=done item=2 at=1.500 elapsed=1.500 signal=1") == 1, + "trace: wait done line"); + check(count(log, "x2w-input-trace mark label=start item=1 at=0.000 present=10") == 1, "trace: start mark line"); + check(count(log, "x2w-input-trace mark label=turn item=5 at=2.500 present=11") == 1, "trace: turn mark line"); + check(count(log, "x2w-input-trace wait event=timeout") == 0, "trace: no timeout line"); + const std::size_t states = count(log, "x2w-input-trace state "); + check(states >= 12 && states <= 20, "trace: bounded state lines (12..20 in four seconds)"); + } else { + check(count(log, trace_prefix) == 0, "control: no x2w-input-trace line without the switch"); + check(count(log, "x2w-input script mark start at 0.000 s (item 1, present 10)") == 1, + "control: the script and its ordinary log still run"); + } + return failures ? 1 : 0; +} + +std::string temp_log_path(const char* suffix) +{ + char temp[MAX_PATH]; + GetTempPathA(MAX_PATH, temp); + return std::string(temp) + "x2w_gameinput_trace_" + suffix + "_" + std::to_string(GetCurrentProcessId()) + ".log"; +} + +int run_mode(const char* self, const char* dll, bool trace) +{ + const std::string log_path = temp_log_path(trace ? "on" : "off"); + DeleteFileA(log_path.c_str()); + SetEnvironmentVariableA("X2W_TRAP_LOG", log_path.c_str()); + SetEnvironmentVariableA("X2W_INPUT_TRACE", trace ? "1" : "0"); + SetEnvironmentVariableA("X2W_INPUT_SCRIPT", script_text); + clear_shared_pad(); + + const std::string command = std::string("\"") + self + "\" \"" + dll + "\" child " + (trace ? "trace" : "control"); + STARTUPINFOA startup{sizeof(startup)}; + PROCESS_INFORMATION process{}; + if (!CreateProcessA(nullptr, const_cast(command.c_str()), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, + &process)) { + std::printf("CreateProcess(%s) failed: %lu\n", trace ? "trace" : "control", GetLastError()); + return 2; + } + DWORD code = 1; + if (WaitForSingleObject(process.hProcess, 60000) != WAIT_OBJECT_0) { + TerminateProcess(process.hProcess, 1); + std::printf("%s child timed out\n", trace ? "trace" : "control"); + } + GetExitCodeProcess(process.hProcess, &code); + CloseHandle(process.hThread); + CloseHandle(process.hProcess); + if (code != 0) { + const std::string log = read_log(log_path); + std::printf("%s child failed (exit %lu), log follows:\n%.4000s\n", trace ? "trace" : "control", code, log.c_str()); + DeleteFileA(log_path.c_str()); + return 1; + } + std::printf("PASS: startup_gameinput_trace %s\n", trace ? "trace" : "control"); + DeleteFileA(log_path.c_str()); + return 0; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc < 2) { + std::printf("usage: startup_gameinput_trace [child trace|control]\n"); + return 2; + } + if (argc >= 4 && std::strcmp(argv[2], "child") == 0) { + if (std::strcmp(argv[3], "trace") != 0 && std::strcmp(argv[3], "control") != 0) { + std::printf("unknown child mode %s\n", argv[3]); + return 2; + } + return run_child(argv[1], std::strcmp(argv[3], "trace") == 0); + } + if (xinput_pad_connected()) { + std::printf("SKIP: XInput pad 0 is connected; its values merge into every reading\n"); + return 77; + } + char self[MAX_PATH]{}; + if (!GetModuleFileNameA(nullptr, self, MAX_PATH)) { + std::printf("GetModuleFileNameA failed: %lu\n", GetLastError()); + return 2; + } + int status = run_mode(self, argv[1], true); + if (!status) status = run_mode(self, argv[1], false); + return status ? status : (failures ? 1 : 0); +} From ec324f73590b8387e23651b664a0e99da874b738 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 20:23:17 +0000 Subject: [PATCH 17/44] tooling: add a startup UI regression matrix --- .../startup-ui-regression-matrix.md | 99 +++++ .../startup_ui_regression_matrix.txt | 1 + tests/startup_ui_regression_matrix_check.py | 255 +++++++++++ tools/startup/ui_regression_matrix.py | 420 ++++++++++++++++++ 4 files changed, 775 insertions(+) create mode 100644 docs/experiments/startup-ui-regression-matrix.md create mode 100644 tests/checks/python-linux/startup_ui_regression_matrix.txt create mode 100644 tests/startup_ui_regression_matrix_check.py create mode 100644 tools/startup/ui_regression_matrix.py diff --git a/docs/experiments/startup-ui-regression-matrix.md b/docs/experiments/startup-ui-regression-matrix.md new file mode 100644 index 0000000000..1f30e8fa55 --- /dev/null +++ b/docs/experiments/startup-ui-regression-matrix.md @@ -0,0 +1,99 @@ +# Startup UI regression matrix + +This note describes a report tool for the startup UI sampler, BC7 and indexed-rectangle work. It runs +existing CTest cases and does not change the runtime, the shaders or the fixtures. The matrix is a +way to collect comparable pass, skip and fail rows across builds; it is not a new rendering +measurement. + +The default rows are: + +| CTest family | Related change | What the fixture measures | +|---|---|---| +| startup_sampler_heap_wrapped_{warp,hardware} | #3153 | The wrapped D3D12 path creates a three-record sampler heap at the title's 16-byte stride, returns the title CPU handle, creates two distinct samplers, copies a record and a two-record range, and checks the destination words. The test enables X2W_D3D12_PERMISSIVE=1 and X2W_D3D12_DEBUG=1. | +| startup_xg_bc7_draw_{warp,hardware} | #3153 | A source-built BC7 surface is uploaded through the wrapped XG path with X2W_XG_BC7_4K_S_LAYOUT=1. The draw checks a 64x64 surface (4,096 pixels) and the visible part of an 81x69 surface (5,589 pixels), for both linear and 4 KiB tiled backing. | +| startup_rect_gap_{warp,hardware} | #3142 | A synthetic eight-record, 12-byte-stride stream is drawn as an R16 indexed triangle list and as six- and eight-vertex rectangle lists. A mask-controlled pixel shader and a constant-colour control distinguish coverage from attribute interpolation. The check compares all 32 target pixels with a point-in-triangle model, including a 15-degree rotation and the back-face-culling control. | +| startup_ui_texture_bands_{warp,hardware} | #3141 | A source-built 32x32, three-mip RGBA8 texture follows an indexed gradient draw and an indexed textured UI draw. The stage-by-stage check covers a linear CopyTextureRegion reference, a slot-133 copy, a compact small-texture path, and slot-70 0x105/0x10a layouts, with wrong-row-pitch negative controls. | + +The first two families are registered in the base tree used for this note. startup_rect_gap is +registered by PR #3142 and startup_ui_texture_bands by PR #3141. A build that contains only one of +those changes reports only the families it registers; the matrix does not invent missing tests. + +## Run it + +From the repository root on Windows, enter the developer environment and build the selected +configuration: + +~~~powershell +.\tools\dev.ps1 +cmake --preset dev +cmake --build --preset dev +~~~ + +List the fixture names that this build actually registers: + +~~~powershell +ctest --preset dev -N -R '^(startup_sampler_heap_wrapped|startup_xg_bc7_draw|startup_rect_gap|startup_ui_texture_bands)_(warp|hardware)$' +~~~ + +Run the default matrix: + +~~~powershell +python -B tools/startup/ui_regression_matrix.py ` + --build-dir out/build/dev ` + --json out/ui-regression-matrix.json ` + --output out/ui-regression-matrix.md +~~~ + +The script accepts --ctest for a CTest executable, --adapter warp or --adapter hardware to restrict +the rows, and --filter (or one positional filter) for a CTest name regex. For example, this run +reports only the rotated-rectangle regression introduced by PR #3142: + +~~~powershell +python -B tools/startup/ui_regression_matrix.py ` + --build-dir out/build/dev ` + --filter '^startup_rect_geometry_(warp|hardware)$' ` + --json out/rect-geometry-matrix.json ` + --output out/rect-geometry-matrix.md +~~~ + +The tool first asks CTest for the matching names with --show-only=json-v1, applies the adapter +filter to that list, and then runs exactly those names with -R. It reads CTest's JUnit report, so +a CTest testcase with no failure or skip marker is the only thing counted as a pass. A testcase +marked notrun or carrying a skipped element is a skip; a failure or error is a fail. The Markdown +table keeps the three states visible and the JSON object has the same rows plus the summary counts +and the CTest command. + +Exit status is 0 when every selected row passed, 1 when at least one row failed, 3 when there were +no failures but at least one skip, and 2 for a malformed or empty selection, a missing CTest +executable or a build that produced no usable JUnit report. A skip therefore never turns a matrix +green. A selected build with no matching tests is rejected before any output is written. + +## What remains a limit + +- The matrix observes the fixtures registered by the current build. It does not merge PR #3141 or + PR #3142, and a family absent from that build is not a failure row. +- startup_rect_gap does not reproduce the exact indexed UI draw from issue #3131. Its synthetic + input passes without showing the reported diagonal gap. The fixed rotated-corner case is in + startup_rect_geometry; the #3142 note records the remaining unverified candidates. +- startup_ui_texture_bands demonstrates the tested upload and sampling routes. It does not prove + that the original UI draw in #3132 has the same input, texture layout or draw path. +- The adapter suffix in a CTest name is the requested backend. It is not proof that the runtime + selected that device: the rectangle fixture, for example, can report the Microsoft Basic Render + Driver for a hardware invocation. Record the observed adapter, driver, Windows build and + debug-layer status separately when a row is used as hardware evidence. +- A skip is a capability or environment result, not a pass. The JUnit report does not preserve the + process exit code for every CTest version, so the matrix does not label a generic skip as 77; + the CTest SKIP_RETURN_CODE property is what makes a 77 a skip. +- The matrix does not run the full startup, does not load game files and does not establish a + playable port or a frame rate. + +## References + +- [PR #3153: runtime: restore menu sampler bindings and BC7 display uploads](https://github.com/R0Y00/Xbox2Windows/pull/3153) +- [PR #3141: runtime: trace UI texture row-pitch bands and fix XG mip-0 and CopyTextureRegion tracking](https://github.com/R0Y00/Xbox2Windows/pull/3141) +- [PR #3142: startup: identify a rotated rectangle corner by its diagonal](https://github.com/R0Y00/Xbox2Windows/pull/3142) +- [Issue #3131: native UI gradient draw leaves a diagonal gap](https://github.com/R0Y00/Xbox2Windows/issues/3131) +- [Issue #3132: horizontal color bands from a textured UI draw](https://github.com/R0Y00/Xbox2Windows/issues/3132) + +The PRs provide the regression matrix and its fixtures. This note makes no closing claim for +#3131 or #3132; those conversations remain with the authors and reviewers of the respective PRs. diff --git a/tests/checks/python-linux/startup_ui_regression_matrix.txt b/tests/checks/python-linux/startup_ui_regression_matrix.txt new file mode 100644 index 0000000000..48d880d0c9 --- /dev/null +++ b/tests/checks/python-linux/startup_ui_regression_matrix.txt @@ -0,0 +1 @@ +tests/startup_ui_regression_matrix_check.py diff --git a/tests/startup_ui_regression_matrix_check.py b/tests/startup_ui_regression_matrix_check.py new file mode 100644 index 0000000000..b8c907fe27 --- /dev/null +++ b/tests/startup_ui_regression_matrix_check.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +"""Check tools/startup/ui_regression_matrix.py with a fake CTest executable. + +The fixture covers a full mixed matrix, a 77 capability skip, a failure, an +adapter-only selection, a custom filter and empty selections. It runs without +CMake, D3D12 or game files. +""" + +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + + +ROOT = Path(__file__).resolve().parent.parent +MATRIX = ROOT / "tools" / "startup" / "ui_regression_matrix.py" + +FAKE_CTEST = r'''#!/usr/bin/env python3 +"""Small CTest stand-in: list tests as JSON and write a CTest-shaped JUnit file.""" +import datetime +import json +import os +from pathlib import Path +import re +import sys +import xml.etree.ElementTree as ET + + +def option(args, name): + try: + return args[args.index(name) + 1] + except (ValueError, IndexError): + raise SystemExit("fake ctest: missing %s" % name) + + +args = sys.argv[1:] +scenario_path = Path(os.environ["UI_MATRIX_SCENARIO"]) +record_path = Path(os.environ["UI_MATRIX_INVOCATIONS"]) +tests = json.loads(scenario_path.read_text(encoding="utf-8"))["tests"] +with record_path.open("a", encoding="utf-8") as record: + record.write(json.dumps(args) + "\n") + +pattern = option(args, "-R") if "-R" in args else ".*" +selected = [test for test in tests if re.search(pattern, test["name"])] + +if "--show-only=json-v1" in args: + print(json.dumps({ + "kind": "ctestInfo", + "version": {"major": 3, "minor": 31, "patch": 0}, + "tests": [{"name": test["name"]} for test in selected], + })) + raise SystemExit(0) + +junit = Path(option(args, "--output-junit")) +if not selected: + print("No tests were found!!!", file=sys.stderr) + raise SystemExit(8) + +failures = sum(test.get("status") == "fail" for test in selected) +skips = sum(test.get("status") == "skip" for test in selected) +duration = sum(float(test.get("duration", 0)) for test in selected) +root = ET.Element("testsuite", { + "name": "fake-ctest", + "tests": str(len(selected)), + "failures": str(failures), + "errors": "0", + "skipped": str(skips), + "time": "%.3f" % duration, + "timestamp": datetime.datetime.now().astimezone().isoformat(timespec="seconds"), +}) +for test in selected: + status = test.get("status", "pass") + case = ET.SubElement(root, "testcase", { + "name": test["name"], + "status": "run" if status == "pass" else "fail" if status == "fail" else "notrun", + "time": str(test.get("duration", 0)), + }) + detail = str(test.get("detail", "")) + if status == "skip": + ET.SubElement(case, "skipped", {"message": detail or "exit code 77: skipped"}) + elif status == "fail": + ET.SubElement(case, "failure", {"message": detail or "failure"}).text = detail + +ET.ElementTree(root).write(junit, encoding="utf-8", xml_declaration=True) +print("%d tests ran" % len(selected)) +raise SystemExit(1 if failures else 0) +''' + + +def test_case(name, status, detail="", duration=0.1): + return {"name": name, "status": status, "detail": detail, "duration": duration} + + +FULL_SCENARIO = { + "tests": [ + test_case("startup_sampler_heap_wrapped_warp", "pass", duration=0.2), + test_case( + "startup_sampler_heap_wrapped_hardware", + "skip", + "exit code 77: hardware adapter unavailable", + ), + test_case( + "startup_xg_bc7_draw_warp", + "fail", + "pixel (4, 0): read 000000ff, expected ff0000ff", + duration=1.5, + ), + test_case( + "startup_xg_bc7_draw_hardware", + "skip", + "exit code 77: D3D12 feature level 12 unavailable", + ), + test_case("startup_rect_gap_warp", "pass", duration=0.3), + test_case("startup_rect_gap_hardware", "skip", "exit code 77: no physical adapter"), + test_case("startup_ui_texture_bands_warp", "pass", duration=0.4), + test_case( + "startup_ui_texture_bands_hardware", + "skip", + "exit code 77: D3D12 debug layer unavailable", + ), + ] +} + + +class Fixture: + def __init__(self, root): + self.root = Path(root) + self.build = self.root / "build" + self.build.mkdir() + self.fake = self.root / "fake_ctest.py" + self.fake.write_text(FAKE_CTEST, encoding="utf-8") + self.serial = 0 + + def run(self, scenario, *extra, expect_outputs=True): + self.serial += 1 + stem = "matrix-%d" % self.serial + scenario_path = self.root / (stem + ".scenario.json") + invocations = self.root / (stem + ".invocations.jsonl") + output = self.root / (stem + ".md") + report = self.root / (stem + ".json") + scenario_path.write_text(json.dumps(scenario), encoding="utf-8") + env = dict(os.environ, UI_MATRIX_SCENARIO=str(scenario_path), + UI_MATRIX_INVOCATIONS=str(invocations)) + command = [ + sys.executable, "-B", str(MATRIX), + "--build-dir", str(self.build), + "--ctest", str(self.fake), + "--json", str(report), + "--output", str(output), + *extra, + ] + proc = subprocess.run( + command, + cwd=ROOT, + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + errors="replace", + timeout=30, + ) + calls = [] + if invocations.is_file(): + calls = [json.loads(line) for line in invocations.read_text(encoding="utf-8").splitlines()] + if expect_outputs: + assert output.is_file(), proc.stderr + assert report.is_file(), proc.stderr + return proc, output, report, calls + + +def rows(markdown, names): + found = {} + for name in names: + matches = [line for line in markdown.splitlines() if name in line] + assert len(matches) == 1, (name, matches) + found[name] = matches[0] + return found + + +def main(): + with tempfile.TemporaryDirectory() as temporary: + fixture = Fixture(temporary) + names = [test["name"] for test in FULL_SCENARIO["tests"]] + + proc, output, report, calls = fixture.run(FULL_SCENARIO) + assert proc.returncode == 1, (proc.returncode, proc.stdout, proc.stderr) + assert len(calls) == 2, calls + data = json.loads(report.read_text(encoding="utf-8")) + assert data["summary"] == {"selected": 8, "passed": 3, "skipped": 4, "failed": 1}, data + statuses = {item["name"]: item["status"] for item in data["tests"]} + assert statuses["startup_sampler_heap_wrapped_hardware"] == "skip", statuses + assert statuses["startup_xg_bc7_draw_warp"] == "fail", statuses + skipped = next(item for item in data["tests"] + if item["name"] == "startup_sampler_heap_wrapped_hardware") + assert "77" in skipped["detail"], skipped + markdown = output.read_text(encoding="utf-8") + table = rows(markdown, names) + assert "| PASS |" in table["startup_sampler_heap_wrapped_warp"], table + assert "| SKIP |" in table["startup_sampler_heap_wrapped_hardware"], table + assert "| FAIL |" in table["startup_xg_bc7_draw_warp"], table + assert "not a pass" in markdown, markdown + + proc, output, report, _ = fixture.run( + FULL_SCENARIO, "--filter", "^startup_rect_gap_hardware$") + assert proc.returncode == 3, (proc.returncode, proc.stdout, proc.stderr) + data = json.loads(report.read_text(encoding="utf-8")) + assert data["summary"] == {"selected": 1, "passed": 0, "skipped": 1, "failed": 0}, data + assert "| SKIP |" in output.read_text(encoding="utf-8") + + proc, output, report, _ = fixture.run( + FULL_SCENARIO, "--filter", "^startup_rect_gap_warp$") + assert proc.returncode == 0, (proc.returncode, proc.stdout, proc.stderr) + data = json.loads(report.read_text(encoding="utf-8")) + assert data["summary"] == {"selected": 1, "passed": 1, "skipped": 0, "failed": 0}, data + + proc, output, report, calls = fixture.run(FULL_SCENARIO, "--adapter", "warp") + assert proc.returncode == 1, (proc.returncode, proc.stdout, proc.stderr) + data = json.loads(report.read_text(encoding="utf-8")) + assert data["summary"] == {"selected": 4, "passed": 3, "skipped": 0, "failed": 1}, data + assert all(item["adapter"] == "warp" for item in data["tests"]), data + selected_run = calls[-1] + exact = selected_run[selected_run.index("-R") + 1] + assert "hardware" not in exact, exact + + proc, output, report, _ = fixture.run( + FULL_SCENARIO, "--filter", "^startup_ui_texture_bands_") + assert proc.returncode == 3, (proc.returncode, proc.stdout, proc.stderr) + data = json.loads(report.read_text(encoding="utf-8")) + assert data["summary"] == {"selected": 2, "passed": 1, "skipped": 1, "failed": 0}, data + + proc, output, report, _ = fixture.run({"tests": []}, expect_outputs=False) + assert proc.returncode == 2, (proc.returncode, proc.stdout, proc.stderr) + assert "no CTest tests matched" in proc.stderr, proc.stderr + assert not output.exists() and not report.exists() + + proc, output, report, _ = fixture.run( + FULL_SCENARIO, "--filter", "^startup_rect_gap_warp$", "--adapter", "hardware", + expect_outputs=False) + assert proc.returncode == 2, (proc.returncode, proc.stdout, proc.stderr) + assert "no CTest tests matched" in proc.stderr, proc.stderr + + proc, output, report, calls = fixture.run( + FULL_SCENARIO, "--filter", "", expect_outputs=False) + assert proc.returncode == 2, (proc.returncode, proc.stdout, proc.stderr) + assert "must not be empty" in proc.stderr, proc.stderr + assert not calls + + print("startup_ui_regression_matrix_check: ok") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/startup/ui_regression_matrix.py b/tools/startup/ui_regression_matrix.py new file mode 100644 index 0000000000..06274dfbfc --- /dev/null +++ b/tools/startup/ui_regression_matrix.py @@ -0,0 +1,420 @@ +#!/usr/bin/env python3 +"""Run the startup UI CTest fixtures and write a Markdown/JSON regression matrix. + +The default selection covers the sampler/BC7 fixes from #3153, the XG mip-0 and +CopyTextureRegion paths from #3141, and the indexed rectangle fixture from #3142. +Only tests registered in the supplied build are run. A test process that exits +with 77 is reported by CTest as skipped when its CTest property says so; this +tool keeps that state separate from both pass and fail. +""" + +from __future__ import annotations + +import argparse +import datetime as datetime_module +import json +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +import xml.etree.ElementTree as ET + + +DEFAULT_FILTER = ( + r"^(startup_sampler_heap_wrapped|startup_xg_bc7_draw|startup_rect_gap|" + r"startup_ui_texture_bands)_(warp|hardware)$" +) +ADAPTERS = ("warp", "hardware") +PASS = "pass" +SKIP = "skip" +FAIL = "fail" + +EXIT_OK = 0 +EXIT_FAILED = 1 +EXIT_USAGE = 2 +EXIT_INCOMPLETE = 3 + + +class MatrixError(Exception): + """A setup or selection error that prevents a trustworthy matrix.""" + + +def _ctest_command(value: str) -> list[str]: + """Resolve --ctest to a command; a .py fixture runs under this interpreter.""" + value = value.strip() + if not value: + raise MatrixError("--ctest must not be empty") + candidate = Path(value).expanduser() + if candidate.is_file(): + path = candidate.resolve() + if path.suffix.lower() == ".py": + return [sys.executable, "-B", str(path)] + return [str(path)] + found = shutil.which(value) + if found: + return [found] + raise MatrixError(f"CTest executable not found: {value}") + + +def _run(command: list[str], build_dir: Path) -> subprocess.CompletedProcess[str]: + try: + return subprocess.run( + command, + cwd=build_dir, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + encoding="utf-8", + errors="replace", + check=False, + ) + except OSError as error: + raise MatrixError(f"cannot run {command[0]!r}: {error}") from error + + +def _diagnostic(proc: subprocess.CompletedProcess[str]) -> str: + text = (proc.stderr or "").strip() or (proc.stdout or "").strip() + if not text: + return f"exit code {proc.returncode}" + tail = text.splitlines()[-8:] + return "\n".join(tail)[:2000] + + +def selected_test_names(ctest: list[str], build_dir: Path, pattern: str) -> list[str]: + """Return the CTest names matching pattern, in CTest's reported order.""" + proc = _run([*ctest, "--show-only=json-v1", "-R", pattern], build_dir) + if proc.returncode != 0: + raise MatrixError(f"CTest could not list tests (exit {proc.returncode}):\n{_diagnostic(proc)}") + text = proc.stdout.lstrip("\ufeff \r\n\t") + start = text.find("{") + if start < 0: + raise MatrixError("CTest --show-only=json-v1 did not return JSON:\n" + text[-2000:]) + try: + listing = json.loads(text[start:]) + except json.JSONDecodeError as error: + raise MatrixError(f"invalid CTest JSON listing: {error}") from error + tests = listing.get("tests") if isinstance(listing, dict) else None + if not isinstance(tests, list): + raise MatrixError("CTest JSON listing has no tests array") + names = [] + seen = set() + for test in tests: + name = test.get("name") if isinstance(test, dict) else None + if not isinstance(name, str) or not name.strip(): + raise MatrixError("CTest JSON listing contains a test without a name") + if name not in seen: + seen.add(name) + names.append(name) + return names + + +def adapter_of(name: str) -> str | None: + for adapter in ADAPTERS: + if name.endswith("_" + adapter): + return adapter + return None + + +def _exact_filter(names: list[str]) -> str: + return "^(" + "|".join(re.escape(name) for name in names) + ")$" + + +def _node_detail(case: ET.Element) -> str: + for tag in ("failure", "error", "skipped"): + node = case.find(tag) + if node is None: + continue + pieces = [] + message = (node.get("message") or "").strip() + if message: + pieces.append(message) + text = (node.text or "").strip() + if text and text != message: + pieces.append(text) + return "\n".join(pieces)[:4000] + return "" + + +def _duration(case: ET.Element) -> float | None: + try: + value = float(case.get("time", "")) + except (TypeError, ValueError): + return None + return value if value >= 0 else None + + +def _case_status(case: ET.Element) -> tuple[str, str]: + """Classify a CTest JUnit case without treating an unknown state as a pass.""" + status = case.get("status", "") + if case.find("failure") is not None or case.find("error") is not None: + return FAIL, _node_detail(case) or "CTest reported a failure" + if case.find("skipped") is not None or status == "notrun": + return SKIP, _node_detail(case) or "CTest reported a skip" + if status == "run": + return PASS, "" + return FAIL, f"unrecognized CTest result status {status!r}" + + +def read_junit(junit: Path) -> list[dict[str, object]]: + try: + root = ET.parse(junit).getroot() + except (ET.ParseError, OSError) as error: + raise MatrixError(f"cannot read CTest JUnit report {junit}: {error}") from error + if root.tag != "testsuite": + raise MatrixError(f"expected a single CTest root, found <{root.tag}>") + results = [] + for case in root.iter("testcase"): + name = (case.get("name") or "").strip() + if not name: + raise MatrixError("CTest JUnit contains a testcase without a name") + status, detail = _case_status(case) + results.append({ + "name": name, + "adapter": adapter_of(name), + "status": status, + "duration_seconds": _duration(case), + "detail": detail, + }) + return results + + +def run_tests( + ctest: list[str], build_dir: Path, names: list[str] +) -> tuple[list[dict[str, object]], int, list[str]]: + """Run exactly names and return results, CTest exit status and its command.""" + exact = _exact_filter(names) + with tempfile.TemporaryDirectory(prefix="x2w-ui-matrix-") as temporary: + junit = Path(temporary) / "ctest-junit.xml" + command = [ + *ctest, + "--output-junit", + str(junit), + "--output-on-failure", + "--no-tests=error", + "-R", + exact, + ] + proc = _run(command, build_dir) + if not junit.is_file(): + if "No tests were found" in (proc.stdout or "") + (proc.stderr or ""): + raise MatrixError("CTest selected no tests") + raise MatrixError( + f"CTest did not write a JUnit report (exit {proc.returncode}):\n{_diagnostic(proc)}" + ) + results = read_junit(junit) + by_name = {str(item["name"]): item for item in results} + missing = [name for name in names if name not in by_name] + if missing: + raise MatrixError("CTest did not report: " + ", ".join(missing)) + if not results: + raise MatrixError("CTest selected no tests") + # Keep exactly the selected order; a concurrent registration cannot inject a row. + ordered = [by_name[name] for name in names] + return ordered, proc.returncode, command + + +def _source_commit() -> str | None: + root = Path(__file__).resolve().parents[2] + try: + proc = subprocess.run( + ["git", "-C", str(root), "rev-parse", "HEAD"], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + encoding="utf-8", + errors="replace", + check=False, + ) + except OSError: + return None + value = proc.stdout.strip() + return value if proc.returncode == 0 and re.fullmatch(r"[0-9a-f]{40,64}", value) else None + + +def summarize(results: list[dict[str, object]]) -> dict[str, int]: + return { + "selected": len(results), + "passed": sum(item["status"] == PASS for item in results), + "skipped": sum(item["status"] == SKIP for item in results), + "failed": sum(item["status"] == FAIL for item in results), + } + + +def _display_path(path: Path) -> str: + try: + return str(path.resolve()) + except OSError: + return str(path) + + +def _md_code(value: str) -> str: + return "`" + value.replace("`", "'") + "`" + + +def _short_detail(value: object, limit: int = 260) -> str: + text = " ".join(str(value or "").split()) + if len(text) > limit: + text = text[:limit - 3].rstrip() + "..." + return text.replace("|", "\\|") + + +def markdown_report( + build_dir: Path, + selection: str, + adapter: str, + ctest_returncode: int, + results: list[dict[str, object]], + summary: dict[str, int], +) -> str: + lines = [ + "# Startup UI regression matrix", + "", + f"- Build directory: {_md_code(_display_path(build_dir))}", + f"- Selection: {_md_code(selection)}", + f"- Adapter: {_md_code(adapter)}", + f"- CTest exit code: {ctest_returncode}", + f"- Result: {summary['passed']} passed, {summary['skipped']} skipped, " + f"{summary['failed']} failed ({summary['selected']} selected)", + "", + "| Test | Result | Time | Detail |", + "| --- | --- | ---: | --- |", + ] + for item in results: + status = str(item["status"]).upper() + duration = item["duration_seconds"] + when = f"{duration:.3f} s" if isinstance(duration, float) else "-" + lines.append( + f"| {_md_code(str(item['name']))} | {status} | {when} | " + f"{_short_detail(item['detail'])} |" + ) + lines += [ + "", + "A skipped fixture did not complete its measurement. It is not a pass; " + "its capability or environment requirement has to be satisfied before " + "that row can support a result.", + "", + ] + return "\n".join(lines) + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description=( + "Run selected startup UI CTest fixtures and write pass/skip/fail " + "Markdown and JSON matrices. Empty selections are errors." + ) + ) + parser.add_argument( + "--build-dir", + type=Path, + default=Path("out/build/dev"), + help="CMake build directory (default: out/build/dev)", + ) + parser.add_argument( + "--ctest", + default="ctest", + help="CTest executable, or a Python fixture script (default: ctest)", + ) + parser.add_argument( + "--adapter", + choices=("all",) + ADAPTERS, + default="all", + help="restrict rows to tests ending _warp or _hardware (default: all)", + ) + parser.add_argument("--json", type=Path, help="write the matrix as JSON") + parser.add_argument("--output", type=Path, help="write the matrix as Markdown") + parser.add_argument( + "--filter", + dest="filter_option", + help="CTest name regex; default is the sampler/BC7/rect/bands matrix", + ) + parser.add_argument( + "positional_filter", + nargs="?", + metavar="FILTER", + help="CTest name regex (alternative to --filter)", + ) + return parser + + +def _write(path: Path, content: str) -> None: + path = path.expanduser() + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + + +def main(argv: list[str] | None = None) -> int: + parser = build_parser() + args = parser.parse_args(argv) + if args.filter_option is not None and args.positional_filter is not None: + parser.error("give the filter either positionally or with --filter, not both") + selection = args.filter_option if args.filter_option is not None else args.positional_filter + if selection is None: + selection = DEFAULT_FILTER + if not selection.strip(): + parser.error("the filter must not be empty") + + build_dir = args.build_dir.expanduser().resolve() + if not build_dir.is_dir(): + parser.error(f"build directory does not exist: {build_dir}") + try: + ctest = _ctest_command(args.ctest) + except MatrixError as error: + parser.error(str(error)) + + try: + names = selected_test_names(ctest, build_dir, selection) + if args.adapter != "all": + names = [name for name in names if adapter_of(name) == args.adapter] + if not names: + raise MatrixError( + f"no CTest tests matched the selection for adapter {args.adapter!r}: {selection}" + ) + results, ctest_returncode, command = run_tests(ctest, build_dir, names) + except MatrixError as error: + print(f"ui_regression_matrix: error: {error}", file=sys.stderr) + return EXIT_USAGE + + summary = summarize(results) + markdown = markdown_report(build_dir, selection, args.adapter, ctest_returncode, results, summary) + payload = { + "schema": "xbox2windows-startup-ui-regression-matrix-v1", + "generated_at": datetime_module.datetime.now( + datetime_module.timezone.utc + ).isoformat(timespec="seconds"), + "source_commit": _source_commit(), + "build_dir": _display_path(build_dir), + "ctest": args.ctest, + "ctest_command": command, + "ctest_returncode": ctest_returncode, + "selection": selection, + "adapter": args.adapter, + "tests": results, + "summary": summary, + } + + if args.output: + _write(args.output, markdown) + print(f"ui_regression_matrix: wrote {args.output}") + else: + print(markdown) + if args.json: + _write(args.json, json.dumps(payload, indent=2) + "\n") + print(f"ui_regression_matrix: wrote {args.json}") + print( + "ui_regression_matrix: " + f"{summary['passed']} passed, {summary['skipped']} skipped, " + f"{summary['failed']} failed ({summary['selected']} selected)" + ) + + if summary["failed"]: + return EXIT_FAILED + if summary["skipped"]: + return EXIT_INCOMPLETE + return EXIT_OK + + +if __name__ == "__main__": + sys.exit(main()) From 83d36dbf25dd0d058b1210ef7a63e060d657254a Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 20:23:47 +0000 Subject: [PATCH 18/44] tooling: report the first scene-colour write from draw dumps --- docs/experiments.md | 4 +- .../experiments/startup-scene-color-report.md | 112 +++ .../python-linux/scene_color_report.txt | 1 + tests/startup_scene_color_report_check.py | 273 ++++++ tools/startup/scene_color_report.py | 832 ++++++++++++++++++ 5 files changed, 1221 insertions(+), 1 deletion(-) create mode 100644 docs/experiments/startup-scene-color-report.md create mode 100644 tests/checks/python-linux/scene_color_report.txt create mode 100644 tests/startup_scene_color_report_check.py create mode 100644 tools/startup/scene_color_report.py diff --git a/docs/experiments.md b/docs/experiments.md index 13e4d28d40..001b22bfba 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -186,7 +186,9 @@ written to `pixel_history.txt` in `X2W_DRAW_DUMP_DIR`: `draw=` is the copy ordin frame that recorded it, `x=` and `y=` name the texel, `key=` is the translated manifest key, and `rgba=` is decoded for R8G8B8A8/B8G8R8A8 UNORM or sRGB. The same 48-copy bound as the full dump applies. A reader can follow the value after every draw and -name the one that last changed the texel. +name the one that last changed the texel. [`tools/startup/scene_color_report.py`](../tools/startup/scene_color_report.py) +turns a dump directory into a bounded Markdown report that selects a frame and pixel and names the +first retained change as well as the last writer; see [the report note](experiments/startup-scene-color-report.md). `startup_pixel_history` builds three draws on a 4x4 target. The first and third are scissored to the top-left texel; only the second covers the watched texel (1, 1). The report must name draw 2 with its diff --git a/docs/experiments/startup-scene-color-report.md b/docs/experiments/startup-scene-color-report.md new file mode 100644 index 0000000000..39921b9ecc --- /dev/null +++ b/docs/experiments/startup-scene-color-report.md @@ -0,0 +1,112 @@ +# Startup scene-colour report from per-draw texel history + +Refs [#870](https://github.com/R0Y00/Xbox2Windows/issues/870). This note documents an +offline reader for the draw diagnostics that already exist. No title run was made for +this change, and no dump, game file or GPU result is checked in. + +## Command + +```powershell +python -B tools/startup/scene_color_report.py ` + [--frame ] [--pixel ,] [--baseline-raw <0xRRGGBBAA>] [--max-rows ] +``` + +The directory is the one passed to `X2W_DRAW_DUMP_DIR`. `--frame` and `--pixel` +choose the sample group; without either option the tool selects the largest group +and says so. `--baseline-raw` supplies a known pre-draw word, for the case where +the first retained sample is already the first colour write. + +The tool prints Markdown to standard output. The input path, file names, raw log +lines and arbitrary text never appear in the report. + +## Input + +`pixel_history.txt` starts with `x2w-pixel-history 1 samples=`. Each following +line is written by [`pixel_history_write`](../../src/startup_stubs/pixel_history.h): + +```text +draw= frame= x= y= key=<16 hex> count= format= raw=<8 hex> [rgba=r,g,b,a] +``` + +The runtime records one texel of render target 0 after each translated draw of +`X2W_DRAW_DUMP_FRAME` (and the following frame, when the copy completes there). It +decodes `rgba=` for `R8G8B8A8_UNORM`, `R8G8B8A8_UNORM_SRGB`, `B8G8R8A8_UNORM` and +`B8G8R8A8_UNORM_SRGB`. The copy budget is 48, so a history that reaches 48 samples +may be missing later draws. See [Per-draw texel history](../experiments.md#per-draw-texel-history) +and the [startup runtime options](../startup-runtime.md#environment-variables). + +The `draw=` value is the runtime copy ordinal, not a title draw-call number. It is +monotonic in one process and is used here only to order the retained samples. + +When full-dump BMPs from `X2W_DRAW_DUMP_FRAME` are present, the tool reads their +headers and the selected pixel. The runtime writes either the full BMP set or the +texel history in one run, so the two are never merged: only a BMP with the same +`draw`, `key` and `count` is compared. BMP files carry no frame field. The reader +accepts BI_RGB 24-bit or 32-bit bottom-up or top-down BMPs and ignores the alpha +byte, which the runtime forces to 255. + +## What the report shows + +For the selected frame and pixel it lists the retained samples with frame, copy +ordinal, opaque pipeline key, draw `count`, DXGI format, `raw` word and decoded +`rgba`. It names both the first retained sample whose value differs from the +baseline and the last retained writer, rather than only the final value. + +| Classification | Meaning | +| --- | --- | +| `no_draw` (aucun draw) | No retained sample matches the selected frame and pixel. It does not prove the title issued no draw. | +| `ui_only` (draw UI seulement) | Samples exist, but no retained sample changes the selected pixel. This is an observation, not proof that the draws are UI. | +| `target_write` (écriture de cible) | At least one sample changed the value and the final value differs from the baseline. | +| `value_unchanged` (valeur inchangée) | At least one change was observed, but the final value equals the baseline; also used for one sample with no baseline, where no transition is observable. | +| `history_truncated` (historique tronqué) | The 48-copy cap, the input bound or a header/record-count mismatch was reached. The first and last writers are still reported from the retained samples. | +| `target_non_rgba8` (cible non-RGBA8) | The format is outside the four decodable 8-bit four-channel formats. The raw word is shown, but no colour change is evaluated. | + +The report is bounded: at most 1 MiB of history, 4,096 records, 64 BMPs, eight +sample groups and 64 timeline rows are considered. Timeline rows omitted by the +default 24-row bound are counted. Invalid lines are counted and ignored, never +echoed. When `rgba=` disagrees with `raw`, the decoded value is used and the +mismatch is counted. + +## What it proves and what it does not + +It proves only that, among the translated draws retained in `pixel_history.txt` +for the selected frame and pixel, a particular value appeared after a particular +copy ordinal and changed on a particular later draw. A BMP with the same +`draw`/`key`/`count` confirms the RGB at that pixel. + +It does not replace a run of the title. It does not show that a draw is a scene +draw rather than a UI draw, that a scene was visible, that a clear happened, or +that an untranslated draw was absent. It does not cover render targets other than +target 0, formats other than the four RGBA8/BGRA8 formats, draws after the 48-copy +cap, or the presented image. + +The history has no sample before the first draw. If the first retained draw is +itself the first colour write, the tool cannot see the transition unless the +caller supplies `--baseline-raw`. The report states that limitation next to the +baseline. A frame whose first sample is the known clear colour is the simplest +way to see the first write without an extra baseline. + +## Tests + +```powershell +python -B tests/startup_scene_color_report_check.py +``` + +The synthetic check passes 14 cases: first change and last writer, a first change +that is also the last writer, a write that restores the baseline, no observed +change, an empty history, a malformed line, a non-RGBA8 target, BGRA channel +order, the 48-sample cap with a bounded table, frame and pixel selection, a +supplied baseline, BMP match and mismatch, a header/record mismatch, and a +missing history file. The check is listed in +[`tests/checks/python-linux/scene_color_report.txt`](../../tests/checks/python-linux/scene_color_report.txt) +so the Linux CI job runs it without Windows, a GPU or a dump. + +No local dump was available under `out/` during this change, so the checked +results are synthetic. The tool was not run against the title. + +## Limits + +The parser accepts only the version-1 header and the exact field order above. +The BMP path accepts BI_RGB 24-bit or 32-bit images up to 16,384 pixels per side +and 64 MiB. A 48-sample history is reported as truncated by design, even when the +title happened to stop after exactly 48 copies. diff --git a/tests/checks/python-linux/scene_color_report.txt b/tests/checks/python-linux/scene_color_report.txt new file mode 100644 index 0000000000..1c90868f22 --- /dev/null +++ b/tests/checks/python-linux/scene_color_report.txt @@ -0,0 +1 @@ +tests/startup_scene_color_report_check.py diff --git a/tests/startup_scene_color_report_check.py b/tests/startup_scene_color_report_check.py new file mode 100644 index 0000000000..60671ae993 --- /dev/null +++ b/tests/startup_scene_color_report_check.py @@ -0,0 +1,273 @@ +"""Synthetic histories for tools/startup/scene_color_report.py. + +Refs #870. No dump, title file or GPU is used here. Each case writes the exact +``pixel_history.txt`` shape from ``src/startup_stubs/pixel_history.h`` in a +temporary directory and checks the bounded Markdown result. +""" + +from __future__ import annotations + +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "startup" / "scene_color_report.py" + + +def raw_rgba(red: int, green: int, blue: int, alpha: int, fmt: int = 28) -> int: + """Return the little-endian word pixel_history_decode() reads.""" + if fmt in (87, 91): + return blue | (green << 8) | (red << 16) | (alpha << 24) + return red | (green << 8) | (blue << 16) | (alpha << 24) + + +def sample(draw: int, *, frame: int = 1, x: int = 1, y: int = 1, + key: int = 1, count: int = 3, fmt: int = 28, + rgba: tuple[int, int, int, int] | None = None) -> str: + if rgba is None: + rgba = (0, 0, 0, 0) + raw = raw_rgba(*rgba, fmt=fmt) + line = (f"draw={draw} frame={frame} x={x} y={y} key={key:016x} " + f"count={count} format={fmt} raw={raw:08x}") + if fmt in (28, 29, 87, 91): + line += " rgba=%d,%d,%d,%d" % rgba + return line + + +def history(*lines: str) -> str: + return "x2w-pixel-history 1 samples=%d\n" % len(lines) + "".join(line + "\n" for line in lines) + + +def write_bmp(path: Path, width: int, height: int, + pixels: dict[tuple[int, int], tuple[int, int, int]]) -> None: + """Write the 32-bit bottom-up BI_RGB BMP shape draw_bmp.h produces.""" + body = bytearray() + for y in range(height - 1, -1, -1): + for x in range(width): + red, green, blue = pixels.get((x, y), (0, 0, 0)) + body += bytes((blue, green, red, 255)) + header = struct.pack("<2sIHHI", b"BM", 54 + len(body), 0, 0, 54) + info = struct.pack(" None: + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + + def tearDown(self) -> None: + self.temp.cleanup() + + def dump_dir(self, name: str = "dump") -> Path: + folder = self.root / name + folder.mkdir() + return folder + + def write_history(self, folder: Path, text: str) -> None: + (folder / "pixel_history.txt").write_text(text, encoding="ascii") + + def run_report(self, folder: Path, *args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-B", str(TOOL), str(folder), *args], + capture_output=True, text=True, encoding="utf-8", timeout=30, + ) + + def test_first_change_is_not_the_last_writer(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, rgba=(0, 0, 0, 0), key=0x1111111111111111), + sample(2, rgba=(0, 255, 0, 255), key=0x2222222222222222), + sample(3, rgba=(0, 255, 0, 255), key=0x2222222222222222), + sample(4, rgba=(0, 0, 255, 255), key=0x4444444444444444), + )) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Classification: `target_write`", result.stdout) + self.assertIn("First observed change: `draw=2`", result.stdout) + self.assertIn("Last observed writer: `draw=4`", result.stdout) + self.assertIn("Frame: `1`", result.stdout) + self.assertIn("Pixel: `1,1`", result.stdout) + + def test_last_writer_can_be_the_first_change(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, rgba=(0, 0, 0, 0)), + sample(2, rgba=(0, 255, 0, 255), key=0x2222222222222222), + sample(3, rgba=(0, 255, 0, 255), key=0x2222222222222222), + )) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("First observed change: `draw=2`", result.stdout) + self.assertIn("Last observed writer: `draw=2`", result.stdout) + self.assertIn("first change; last writer", result.stdout) + + def test_value_unchanged_after_a_restore(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, rgba=(0, 0, 0, 0)), + sample(2, rgba=(0, 255, 0, 255), key=0x2222222222222222), + sample(3, rgba=(0, 0, 0, 0), key=0x3333333333333333), + )) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Classification: `value_unchanged`", result.stdout) + self.assertIn("First observed change: `draw=2`", result.stdout) + self.assertIn("Last observed writer: `draw=3`", result.stdout) + + def test_ui_only_when_no_sample_changes(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, rgba=(0, 0, 0, 0)), + sample(2, rgba=(0, 0, 0, 0)), + sample(3, rgba=(0, 0, 0, 0)), + )) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Classification: `ui_only`", result.stdout) + self.assertIn("First observed change: _none among the retained samples", result.stdout) + self.assertIn("Last observed writer: _none_", result.stdout) + + def test_empty_history_is_no_draw(self) -> None: + folder = self.dump_dir() + self.write_history(folder, "x2w-pixel-history 1 samples=0\n") + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Classification: `no_draw`", result.stdout) + self.assertIn("Selected sample group: _none_", result.stdout) + self.assertIn("_No retained sample for the selected frame and pixel._", result.stdout) + + def test_malformed_line_is_ignored_without_echo(self) -> None: + folder = self.dump_dir("private-title-folder") + malformed = "draw=2 frame=1 x=1 y=1 key=2222222222222222 count=3 format=28 raw=00000000 " \ + "C:\\Users\\someone\\secret\\GameName.exe" + self.write_history(folder, history( + sample(1, rgba=(0, 0, 0, 0)), + malformed, + sample(3, rgba=(0, 255, 0, 255), key=0x3333333333333333), + )) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Malformed records ignored: `1`", result.stdout) + self.assertIn("First observed change: `draw=3`", result.stdout) + self.assertNotIn("GameName", result.stdout) + self.assertNotIn("secret", result.stdout) + self.assertNotIn("Users", result.stdout) + self.assertNotIn("private-title-folder", result.stdout) + self.assertNotIn(str(self.root), result.stdout) + + def test_non_rgba8_target_is_not_decoded(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + "draw=1 frame=1 x=1 y=1 key=1111111111111111 count=3 format=10 raw=00000000", + )) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Classification: `target_non_rgba8`", result.stdout) + self.assertIn("First observed change: _not evaluated", result.stdout) + self.assertIn("target is not RGBA8", result.stdout) + + def test_bgra_format_uses_the_documented_channel_order(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, fmt=87, rgba=(255, 0, 0, 255)), + )) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("DXGI_FORMAT_B8G8R8A8_UNORM (`87`)", result.stdout) + self.assertIn("`255,0,0,255`", result.stdout) + + def test_history_cap_marks_truncated_and_bounds_rows(self) -> None: + folder = self.dump_dir() + lines = [sample(1, rgba=(0, 0, 0, 0), key=1)] + for draw in range(2, 49): + lines.append(sample(draw, rgba=(0, 255, 0, 255), key=0x2000000000000000 + draw)) + self.write_history(folder, history(*lines)) + result = self.run_report(folder, "--max-rows", "12") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Classification: `history_truncated`", result.stdout) + self.assertIn("First observed change: `draw=2`", result.stdout) + self.assertIn("History limit: the runtime cap", result.stdout) + timeline = result.stdout.split("## Retained timeline", 1)[1].split("## Input accounting", 1)[0] + rows = [line for line in timeline.splitlines() if line.startswith("| `")] + self.assertLessEqual(len(rows), 12, timeline) + self.assertIn("row(s) omitted", timeline) + + def test_frame_and_pixel_selection(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, frame=1, x=0, y=0, rgba=(0, 0, 0, 0)), + sample(2, frame=1, x=0, y=0, rgba=(0, 255, 0, 255), key=0x2222222222222222), + sample(3, frame=2, x=1, y=1, rgba=(0, 0, 0, 0)), + sample(4, frame=2, x=1, y=1, rgba=(0, 0, 255, 255), key=0x4444444444444444), + sample(5, frame=2, x=1, y=1, rgba=(0, 0, 255, 255), key=0x4444444444444444), + )) + selected = self.run_report(folder, "--frame", "1", "--pixel", "0,0") + self.assertEqual(selected.returncode, 0, selected.stderr) + self.assertIn("Frame: `1`", selected.stdout) + self.assertIn("Pixel: `0,0`", selected.stdout) + self.assertIn("First observed change: `draw=2`", selected.stdout) + + default = self.run_report(folder) + self.assertEqual(default.returncode, 0, default.stderr) + self.assertIn("Frame: `2`", default.stdout) + self.assertIn("Pixel: `1,1`", default.stdout) + + def test_supplied_baseline_can_name_the_first_draw(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, rgba=(0, 255, 0, 255)), + )) + without = self.run_report(folder) + self.assertEqual(without.returncode, 0, without.stderr) + self.assertIn("Classification: `value_unchanged`", without.stdout) + with_baseline = self.run_report(folder, "--baseline-raw", "0x00000000") + self.assertEqual(with_baseline.returncode, 0, with_baseline.stderr) + self.assertIn("Classification: `target_write`", with_baseline.stdout) + self.assertIn("First observed change: `draw=1`", with_baseline.stdout) + + def test_bmp_cross_check_and_mismatch_control(self) -> None: + folder = self.dump_dir() + self.write_history(folder, history( + sample(1, rgba=(0, 0, 0, 0), key=0x1111111111111111), + sample(2, rgba=(0, 255, 0, 255), key=0x2222222222222222), + )) + bmp = folder / "draw_02_2222222222222222_3.bmp" + write_bmp(bmp, 4, 4, {(1, 1): (0, 255, 0)}) + matched = self.run_report(folder) + self.assertEqual(matched.returncode, 0, matched.stderr) + self.assertIn("BMP files: `1` (valid `1`, invalid `0`)", matched.stdout) + self.assertIn("Target dimensions: `4x4`", matched.stdout) + self.assertIn("Matching selected samples: `1` matched", matched.stdout) + + write_bmp(bmp, 4, 4, {(1, 1): (0, 0, 255)}) + mismatched = self.run_report(folder) + self.assertEqual(mismatched.returncode, 0, mismatched.stderr) + self.assertIn("Matching selected samples: `0` matched, `1` mismatched", mismatched.stdout) + self.assertIn("BMP mismatch at `draw=2`", mismatched.stdout) + + def test_header_mismatch_is_bounded(self) -> None: + folder = self.dump_dir() + text = "x2w-pixel-history 1 samples=5\n" + sample(1, rgba=(0, 0, 0, 0)) + "\n" + self.write_history(folder, text) + result = self.run_report(folder) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("Classification: `history_truncated`", result.stdout) + self.assertIn("Header count and physical record count differ", result.stdout) + + def test_missing_history_is_a_controlled_error(self) -> None: + folder = self.dump_dir() + result = self.run_report(folder) + self.assertEqual(result.returncode, 2) + self.assertIn("pixel_history.txt not found", result.stderr) + self.assertNotIn("Traceback", result.stderr) + self.assertEqual(result.stdout, "") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/startup/scene_color_report.py b/tools/startup/scene_color_report.py new file mode 100644 index 0000000000..56e326ae92 --- /dev/null +++ b/tools/startup/scene_color_report.py @@ -0,0 +1,832 @@ +#!/usr/bin/env python3 +"""Build a bounded Markdown report from a per-draw texel history. + +Refs #870. The startup draw dump writes ``pixel_history.txt`` when +``X2W_DRAW_DUMP_FRAME`` and ``X2W_DRAW_DUMP_PIXEL`` are set (see +``src/startup_stubs/pixel_history.h``). This tool turns that history into a +small review artifact for the first scene-colour write: it selects a frame and +a pixel, names the first retained draw whose sample changes the value, and +reports the last retained writer. Full-dump BMPs are read only to check the +selected pixel and the target dimensions; they are not merged into the history. + +The report never copies raw log lines, paths, arbitrary text or game filenames. +Only allowlisted values (numbers, DXGI format names, opaque 64-bit keys and the +fixed labels below) reach the output. + +Uses only the Python 3 standard library. +""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass +from pathlib import Path +import re +import struct +import sys +from typing import Iterable, Sequence + + +TOOL_VERSION = 1 +HISTORY_FILE = "pixel_history.txt" +RUNTIME_SAMPLE_LIMIT = 48 + +MAX_HISTORY_BYTES = 1 << 20 +MAX_HISTORY_RECORDS = 4096 +MAX_LINE_BYTES = 4096 +MAX_BMPS = 64 +MAX_BMP_BYTES = 64 << 20 +MAX_BMP_DIMENSION = 16384 +DEFAULT_MAX_ROWS = 24 +MAX_MAX_ROWS = 64 +MIN_MAX_ROWS = 8 +MAX_GROUPS = 8 + +# DXGI_FORMAT values that pixel_history_decode() can turn into RGBA channels. +# The second member is True when the 32-bit word stores B8G8R8A8. +RGBA8_FORMATS: dict[int, tuple[str, bool]] = { + 28: ("DXGI_FORMAT_R8G8B8A8_UNORM", False), + 29: ("DXGI_FORMAT_R8G8B8A8_UNORM_SRGB", False), + 87: ("DXGI_FORMAT_B8G8R8A8_UNORM", True), + 91: ("DXGI_FORMAT_B8G8R8A8_UNORM_SRGB", True), +} + +CLASS_LABELS = { + "no_draw": "aucun draw", + "ui_only": "draw UI seulement", + "target_write": "écriture de cible", + "value_unchanged": "valeur inchangée", + "history_truncated": "historique tronqué", + "target_non_rgba8": "cible non-RGBA8", +} + +HEADER_RE = re.compile(r"\Ax2w-pixel-history 1 samples=([0-9]+)\Z") +SAMPLE_RE = re.compile( + r"\Adraw=([0-9]+) frame=(-?[0-9]+) x=([0-9]+) y=([0-9]+) " + r"key=([0-9A-Fa-f]{16}) count=([0-9]+) format=([0-9]+) raw=([0-9A-Fa-f]{8})" + r"(?: rgba=([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3}))?\Z" +) +BMP_NAME_RE = re.compile(r"\Adraw_([0-9]+)_([0-9A-Fa-f]{16})_([0-9]+)\.bmp\Z", re.IGNORECASE) + +UINT64_MAX = (1 << 64) - 1 +INT64_MIN = -(1 << 63) +INT64_MAX = (1 << 63) - 1 +UINT32_MAX = (1 << 32) - 1 +INT32_MAX = (1 << 31) - 1 + + +class ReportError(Exception): + """A controlled input error whose text is safe to print.""" + + +@dataclass(frozen=True) +class Sample: + draw: int + frame: int + x: int + y: int + key: int + count: int + format: int + raw: int + rgba: tuple[int, int, int, int] | None + order: int + + +@dataclass +class History: + declared: int + samples: list[Sample] + physical_records: int + malformed: int + read_truncated: bool + header_mismatch: bool + duplicate_draws: int + rgba_mismatches: int + rgba_missing: int + rgba_ignored: int + + @property + def cap_reached(self) -> bool: + return ( + self.read_truncated + or self.header_mismatch + or self.declared >= RUNTIME_SAMPLE_LIMIT + or len(self.samples) >= RUNTIME_SAMPLE_LIMIT + ) + + +@dataclass(frozen=True) +class Group: + frame: int + x: int + y: int + format: int + samples: tuple[Sample, ...] + + +@dataclass(frozen=True) +class BmpInfo: + path: Path + draw: int + key: int + count: int + width: int + height: int + top_down: bool + bits_per_pixel: int + pixel_offset: int + row_bytes: int + file_size: int + + +@dataclass +class BmpSummary: + total: int = 0 + valid: int = 0 + invalid: int = 0 + dimensions: tuple[tuple[int, int], ...] = () + matched: int = 0 + mismatched: int = 0 + out_of_range: int = 0 + unreadable: int = 0 + skipped: int = 0 + mismatch_rows: tuple[tuple[int, str, str], ...] = () + + +def _format_label(fmt: int) -> str: + entry = RGBA8_FORMATS.get(fmt) + if entry is not None: + return entry[0] + return "unknown" + + +def _format_cell(fmt: int) -> str: + return f"{_format_label(fmt)} (`{fmt}`)" + + +def _key_cell(key: int) -> str: + return f"`{key:016x}`" + + +def _raw_cell(raw: int) -> str: + return f"`0x{raw:08x}`" + + +def _rgba_cell(rgba: tuple[int, int, int, int] | None) -> str: + if rgba is None: + return "_n/a_" + return f"`{rgba[0]},{rgba[1]},{rgba[2]},{rgba[3]}`" + + +def decode_rgba(raw: int, fmt: int) -> tuple[int, int, int, int] | None: + """Decode a raw 32-bit word the same way pixel_history_decode() does.""" + entry = RGBA8_FORMATS.get(fmt) + if entry is None: + return None + bgra = entry[1] + if bgra: + return (raw >> 16) & 0xFF, (raw >> 8) & 0xFF, raw & 0xFF, (raw >> 24) & 0xFF + return raw & 0xFF, (raw >> 8) & 0xFF, (raw >> 16) & 0xFF, (raw >> 24) & 0xFF + + +def parse_history(path: Path) -> History: + """Parse pixel_history.txt with bounded reads and strict allowlisted fields.""" + try: + size = path.stat().st_size + with path.open("rb") as handle: + data = handle.read(MAX_HISTORY_BYTES + 1) + except OSError as exc: + raise ReportError("pixel_history.txt is not readable") from exc + + read_truncated = size > MAX_HISTORY_BYTES + if read_truncated: + data = data[:MAX_HISTORY_BYTES] + # Drop a final partial record rather than report it as malformed. + if data and not data.endswith((b"\n", b"\r")): + cut = data.rfind(b"\n") + data = data[:cut] if cut >= 0 else b"" + + lines = data.splitlines() + if not lines: + raise ReportError("pixel_history.txt is empty or has no header") + + try: + header = lines[0].decode("ascii").rstrip("\r") + except UnicodeDecodeError as exc: + raise ReportError("pixel_history.txt has a non-ASCII header") from exc + match = HEADER_RE.fullmatch(header) + if match is None: + raise ReportError("pixel_history.txt has a missing or unsupported header") + declared = int(match.group(1)) + if declared > MAX_HISTORY_RECORDS: + read_truncated = True + + records = lines[1:] + if len(records) > MAX_HISTORY_RECORDS: + read_truncated = True + records = records[:MAX_HISTORY_RECORDS] + physical_records = len(records) + header_mismatch = read_truncated or declared != physical_records + + samples: list[Sample] = [] + malformed = 0 + duplicates = 0 + rgba_mismatches = 0 + rgba_missing = 0 + rgba_ignored = 0 + seen_draws: set[int] = set() + + for order, raw_line in enumerate(records): + if not raw_line or len(raw_line) > MAX_LINE_BYTES: + malformed += 1 + continue + text = raw_line.decode("ascii", "replace").rstrip("\r") + match = SAMPLE_RE.fullmatch(text) + if match is None: + malformed += 1 + continue + try: + draw = int(match.group(1)) + frame = int(match.group(2)) + x = int(match.group(3)) + y = int(match.group(4)) + key = int(match.group(5), 16) + count = int(match.group(6)) + fmt = int(match.group(7)) + raw = int(match.group(8), 16) + declared_rgba = None + if match.group(9) is not None: + declared_rgba = tuple(int(match.group(index)) for index in range(9, 13)) + except (TypeError, ValueError): + malformed += 1 + continue + + if not (0 <= draw <= UINT64_MAX and INT64_MIN <= frame <= INT64_MAX + and 0 <= x <= UINT32_MAX and 0 <= y <= UINT32_MAX + and 0 <= count <= UINT32_MAX and 0 <= fmt <= INT32_MAX + and 0 <= raw <= UINT32_MAX): + malformed += 1 + continue + if declared_rgba is not None and any(channel > 255 for channel in declared_rgba): + malformed += 1 + continue + + decoded = decode_rgba(raw, fmt) + if decoded is None: + if declared_rgba is not None: + rgba_ignored += 1 + elif declared_rgba is None: + rgba_missing += 1 + elif declared_rgba != decoded: + rgba_mismatches += 1 + + if draw in seen_draws: + duplicates += 1 + else: + seen_draws.add(draw) + samples.append(Sample(draw=draw, frame=frame, x=x, y=y, key=key, count=count, + format=fmt, raw=raw, rgba=decoded, order=order)) + + return History( + declared=declared, + samples=samples, + physical_records=physical_records, + malformed=malformed, + read_truncated=read_truncated, + header_mismatch=header_mismatch, + duplicate_draws=duplicates, + rgba_mismatches=rgba_mismatches, + rgba_missing=rgba_missing, + rgba_ignored=rgba_ignored, + ) + + +def build_groups(samples: Iterable[Sample]) -> list[Group]: + grouped: dict[tuple[int, int, int, int], list[Sample]] = {} + for sample in samples: + grouped.setdefault((sample.frame, sample.x, sample.y, sample.format), []).append(sample) + groups = [ + Group(frame=key[0], x=key[1], y=key[2], format=key[3], + samples=tuple(sorted(value, key=lambda item: (item.draw, item.order)))) + for key, value in grouped.items() + ] + groups.sort(key=lambda group: (-len(group.samples), group.frame, group.x, group.y, group.format)) + return groups + + +def select_group(groups: Sequence[Group], frame: int | None, + pixel: tuple[int, int] | None) -> tuple[Group | None, int]: + choices = list(groups) + if frame is not None: + choices = [group for group in choices if group.frame == frame] + if pixel is not None: + choices = [group for group in choices if group.x == pixel[0] and group.y == pixel[1]] + if not choices: + return None, 0 + choices.sort(key=lambda group: (-len(group.samples), group.frame, group.x, group.y, group.format)) + return choices[0], len(choices) + + +def find_baseline(samples: Sequence[Sample], selected: Group) -> Sample | None: + first = selected.samples[0] + best = None + for sample in samples: + if sample.x != selected.x or sample.y != selected.y or sample.format != selected.format: + continue + if (sample.frame, sample.draw, sample.order) >= (first.frame, first.draw, first.order): + continue + if best is None or (sample.draw, sample.order) > (best.draw, best.order): + best = sample + return best + + +def _read_bmp_info(path: Path) -> BmpInfo | None: + try: + size = path.stat().st_size + if size < 54 or size > MAX_BMP_BYTES: + return None + with path.open("rb") as handle: + header = handle.read(54) + except OSError: + return None + if len(header) != 54: + return None + try: + bf_type, _, _, _, bf_off_bits = struct.unpack_from("<2sIHHI", header, 0) + bi_size, width, height, planes, bit_count, compression, _, _, _, _, _ = struct.unpack_from( + " MAX_BMP_DIMENSION or abs(height) > MAX_BMP_DIMENSION: + return None + top_down = height < 0 + rows = abs(height) + row_bytes = ((width * bit_count + 31) // 32) * 4 + if bf_off_bits < 54 or bf_off_bits >= size: + return None + if bf_off_bits + row_bytes * rows > size: + return None + return BmpInfo(path=path, draw=0, key=0, count=0, width=width, height=rows, + top_down=top_down, bits_per_pixel=bit_count, pixel_offset=bf_off_bits, + row_bytes=row_bytes, file_size=size) + + +def _bmp_pixel(info: BmpInfo, x: int, y: int) -> tuple[int, int, int] | None: + if x < 0 or y < 0 or x >= info.width or y >= info.height: + return None + row = y if info.top_down else info.height - 1 - y + offset = info.pixel_offset + row * info.row_bytes + x * (info.bits_per_pixel // 8) + try: + with info.path.open("rb") as handle: + handle.seek(offset) + data = handle.read(info.bits_per_pixel // 8) + except OSError: + return None + if len(data) != info.bits_per_pixel // 8: + return None + return data[2], data[1], data[0] + + +def scan_bmps(folder: Path, selected: Group | None) -> BmpSummary: + summary = BmpSummary() + try: + entries = sorted(entry for entry in folder.iterdir() if entry.is_file()) + except OSError: + return summary + + valid: list[BmpInfo] = [] + for entry in entries: + if summary.total >= MAX_BMPS: + break + name_match = BMP_NAME_RE.fullmatch(entry.name) + if name_match is None: + continue + summary.total += 1 + info = _read_bmp_info(entry) + if info is None: + summary.invalid += 1 + continue + try: + draw = int(name_match.group(1)) + key = int(name_match.group(2), 16) + count = int(name_match.group(3)) + except ValueError: + summary.invalid += 1 + continue + if not (0 <= draw <= UINT64_MAX and 0 <= count <= UINT32_MAX): + summary.invalid += 1 + continue + info = BmpInfo(path=info.path, draw=draw, key=key, count=count, width=info.width, + height=info.height, top_down=info.top_down, + bits_per_pixel=info.bits_per_pixel, pixel_offset=info.pixel_offset, + row_bytes=info.row_bytes, file_size=info.file_size) + valid.append(info) + + summary.valid = len(valid) + summary.dimensions = tuple(sorted({(info.width, info.height) for info in valid})) + if selected is None or not selected.samples: + return summary + + index = {(info.draw, info.key, info.count): info for info in valid} + mismatches: list[tuple[int, str, str]] = [] + for sample in selected.samples: + info = index.get((sample.draw, sample.key, sample.count)) + if info is None: + continue + rgb = _bmp_pixel(info, sample.x, sample.y) + if rgb is None: + if not (0 <= sample.x < info.width and 0 <= sample.y < info.height): + summary.out_of_range += 1 + else: + summary.unreadable += 1 + continue + if sample.rgba is None: + summary.skipped += 1 + continue + expected = sample.rgba[:3] + if rgb == expected: + summary.matched += 1 + else: + summary.mismatched += 1 + if len(mismatches) < 3: + mismatches.append((sample.draw, f"{expected[0]},{expected[1]},{expected[2]}", + f"{rgb[0]},{rgb[1]},{rgb[2]}")) + summary.mismatch_rows = tuple(mismatches) + return summary + + +def _choose_rows(count: int, maximum: int, must: Iterable[int]) -> tuple[list[int], int]: + if count <= maximum: + return list(range(count)), 0 + chosen = {index for index in must if 0 <= index < count} + left, right = 0, count - 1 + while len(chosen) < maximum and left <= right: + chosen.add(left) + left += 1 + if len(chosen) < maximum and left <= right: + chosen.add(right) + right -= 1 + ordered = sorted(chosen) + return ordered, count - len(ordered) + + +def _classification(history: History, selected: Group | None, + baseline_known: bool, baseline_raw: int, + transition_count: int) -> tuple[str, str]: + """Return (primary classification, write outcome).""" + if selected is None or not selected.samples: + return "no_draw", "no_draw" + if selected.format not in RGBA8_FORMATS: + return "target_non_rgba8", "target_non_rgba8" + if transition_count == 0: + if len(selected.samples) == 1 and not baseline_known: + outcome = "value_unchanged" + else: + outcome = "ui_only" + elif selected.samples[-1].raw != baseline_raw: + outcome = "target_write" + else: + outcome = "value_unchanged" + if history.cap_reached: + return "history_truncated", outcome + return outcome, outcome + + +def _render_group_table(groups: Sequence[Group], maximum: int = MAX_GROUPS) -> list[str]: + if not groups: + return ["_No valid history sample._", ""] + lines = [ + "| Frame | Pixel | Format | Samples |", + "| --- | --- | --- | --- |", + ] + for group in groups[:maximum]: + lines.append( + f"| `{group.frame}` | `{group.x},{group.y}` | {_format_cell(group.format)} " + f"| `{len(group.samples)}` |" + ) + if len(groups) > maximum: + lines.append(f"_`{len(groups) - maximum}` more group(s) not shown._") + lines.append("") + return lines + + +def format_report(history: History, groups: Sequence[Group], selected: Group | None, + baseline_sample: Sample | None, baseline_raw: int, + baseline_supplied: bool, bmps: BmpSummary, + max_rows: int, requested_frame: int | None, + requested_pixel: tuple[int, int] | None) -> str: + lines: list[str] = [ + "# Startup scene-colour write report", + "", + f"- Tool: `scene_color_report` v`{TOOL_VERSION}`", + f"- Input: `X2W_DRAW_DUMP_DIR` (path omitted)", + f"- History: `{HISTORY_FILE}` version `1`", + "", + "## Selection", + "", + ] + + if selected is None: + if requested_frame is not None: + lines.append(f"- Requested frame: `{requested_frame}`") + if requested_pixel is not None: + lines.append(f"- Requested pixel: `{requested_pixel[0]},{requested_pixel[1]}`") + lines.extend(["- Selected sample group: _none_", ""]) + else: + lines.extend([ + f"- Frame: `{selected.frame}`", + f"- Pixel: `{selected.x},{selected.y}`", + f"- Format: {_format_cell(selected.format)}", + f"- Retained samples: `{len(selected.samples)}`", + "", + ]) + + if selected is None: + baseline_known = False + transition_count = 0 + first_change = None + last_writer = None + changed_flags: list[bool] = [] + else: + baseline_known = baseline_supplied or baseline_sample is not None + first_change = None + last_writer = None + transition_count = 0 + changed_flags = [] + previous = baseline_raw + for sample in selected.samples: + changed = sample.raw != previous + changed_flags.append(changed) + if changed: + transition_count += 1 + if first_change is None: + first_change = sample + last_writer = sample + previous = sample.raw + + primary, outcome = _classification(history, selected, baseline_known, baseline_raw, + transition_count) + lines.extend([ + "## Classification", + "", + f"- Classification: `{primary}` ({CLASS_LABELS[primary]})", + f"- Write outcome: `{outcome}` ({CLASS_LABELS[outcome]})", + ]) + if selected is not None: + if baseline_supplied: + baseline_text = f"`raw=0x{baseline_raw:08x}` (supplied)" + elif baseline_sample is not None: + baseline_text = (f"`draw={baseline_sample.draw}`, `frame={baseline_sample.frame}`, " + f"`raw=0x{baseline_sample.raw:08x}`") + elif selected.samples: + baseline_text = ("first retained sample; the pre-draw value is not recorded " + f"(`raw=0x{baseline_raw:08x}`)") + else: + baseline_text = "_none_" + lines.append(f"- Baseline: {baseline_text}") + + if selected.format not in RGBA8_FORMATS: + lines.append("- First observed change: _not evaluated (target is not RGBA8)_") + lines.append("- Last observed writer: _not evaluated (target is not RGBA8)_") + elif first_change is None: + if baseline_known: + lines.append("- First observed change: _none_") + else: + lines.append("- First observed change: _none among the retained samples; the first " + "sample is only a baseline_") + lines.append("- Last observed writer: _none_") + else: + lines.append( + f"- First observed change: `draw={first_change.draw}`, `key={first_change.key:016x}`, " + f"`raw=0x{first_change.raw:08x}`, {_rgba_cell(first_change.rgba)}" + ) + lines.append( + f"- Last observed writer: `draw={last_writer.draw}`, `key={last_writer.key:016x}`, " + f"`raw=0x{last_writer.raw:08x}`, {_rgba_cell(last_writer.rgba)}" + ) + if history.cap_reached: + lines.append("- History limit: the runtime cap or input bound was reached; later draws " + "may be missing from the conclusion above.") + lines.append("") + + lines.extend([ + "## Retained timeline", + "", + "Draw ordinals are the runtime copy ordinals (`draw=`), not title draw-call numbers.", + "", + ]) + + if selected is None or not selected.samples: + lines.extend(["_No retained sample for the selected frame and pixel._", ""]) + else: + must = [0, len(selected.samples) - 1] + if first_change is not None: + must.append(selected.samples.index(first_change)) + if last_writer is not None: + must.append(selected.samples.index(last_writer)) + indices, omitted = _choose_rows(len(selected.samples), max_rows, must) + lines.extend([ + "| # | Draw ordinal | Frame | Key | Count | Format | Raw | RGBA | Observation |", + "| --- | --- | --- | --- | --- | --- | --- | --- | --- |", + ]) + for index in indices: + sample = selected.samples[index] + observation = "" + if index == 0 and not baseline_known: + observation = "baseline; pre-draw value unknown" + if changed_flags[index]: + if sample is first_change and sample is last_writer: + observation = "first change; last writer" + elif sample is first_change: + observation = "first change" + elif sample is last_writer: + observation = "last writer" + else: + observation = "change" + lines.append( + f"| `{index + 1}` | `{sample.draw}` | `{sample.frame}` | {_key_cell(sample.key)} " + f"| `{sample.count}` | {_format_cell(sample.format)} | {_raw_cell(sample.raw)} " + f"| {_rgba_cell(sample.rgba)} | {observation} |" + ) + if omitted: + lines.append(f"_`{omitted}` timeline row(s) omitted from this bounded table._") + lines.append("") + + lines.extend([ + "## Input accounting", + "", + f"- Header declares: `{history.declared}` sample(s)", + f"- Physical records: `{history.physical_records}`", + f"- Valid samples: `{len(history.samples)}`", + f"- Malformed records ignored: `{history.malformed}`", + f"- Duplicate draw ordinals: `{history.duplicate_draws}`", + f"- RGBA/raw mismatches: `{history.rgba_mismatches}`", + f"- RGBA omitted on a supported format (decoded from raw): `{history.rgba_missing}`", + f"- RGBA ignored on a non-RGBA8 format: `{history.rgba_ignored}`", + ]) + if history.read_truncated: + lines.append("- Input read: stopped at the built-in byte or record bound") + if history.header_mismatch: + lines.append("- Header count and physical record count differ") + lines.append("") + + lines.extend([ + "## BMP cross-check", + "", + f"- BMP files: `{bmps.total}` (valid `{bmps.valid}`, invalid `{bmps.invalid}`)", + ]) + if bmps.dimensions: + dims = ", ".join(f"`{width}x{height}`" for width, height in bmps.dimensions) + lines.append(f"- Target dimensions: {dims}") + else: + lines.append("- Target dimensions: _not available_") + lines.extend([ + f"- Matching selected samples: `{bmps.matched}` matched, `{bmps.mismatched}` mismatched, " + f"`{bmps.out_of_range}` out of range, `{bmps.unreadable}` unreadable, `{bmps.skipped}` skipped", + ]) + for draw, expected, observed in bmps.mismatch_rows: + lines.append(f"- BMP mismatch at `draw={draw}`: history RGB `{expected}`, BMP RGB `{observed}`") + lines.extend([ + "- BMPs carry no frame field and the runtime writes either the full dump or the texel " + "history, not both; only a matching `draw`/`key`/`count` is compared.", + "", + "## Available groups", + "", + ]) + lines.extend(_render_group_table(groups)) + + lines.extend([ + "## Scope", + "", + "- Reads translated draws recorded for render target 0 only.", + "- Does not run the title, inspect shaders, or prove that a draw is a scene or UI draw.", + "- `ui_only` means draws were retained but no retained sample changed the selected " + "pixel; a scene draw that writes the same value cannot be excluded.", + "- `value_unchanged` means a change was observed but the final retained value equals the " + "baseline, including a write that restores the earlier value.", + "- The first retained sample has no pre-draw value. A write by that first draw is not " + "visible unless a baseline is supplied.", + "- The report says nothing about the presented image or about draws outside the dump window.", + "", + ]) + return "\n".join(lines) + + +def _parse_pixel(value: str) -> tuple[int, int]: + parts = value.split(",") + if len(parts) != 2 or not all(part.isdigit() for part in parts): + raise argparse.ArgumentTypeError("expected X,Y with non-negative decimal integers") + x, y = int(parts[0]), int(parts[1]) + if x > UINT32_MAX or y > UINT32_MAX: + raise argparse.ArgumentTypeError("pixel coordinate is out of range") + return x, y + + +def _parse_raw(value: str) -> int: + try: + raw = int(value, 0) + except ValueError as exc: + raise argparse.ArgumentTypeError("expected a 32-bit integer (for example 0x00000000)") from exc + if not 0 <= raw <= UINT32_MAX: + raise argparse.ArgumentTypeError("raw value is outside 0..0xffffffff") + return raw + + +def _parse_non_negative(value: str) -> int: + if not value.isdigit(): + raise argparse.ArgumentTypeError("expected a non-negative decimal integer") + return int(value) + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser( + prog="scene_color_report.py", + description="Summarize a per-draw texel history into a bounded Markdown report.", + ) + parser.add_argument("dump_dir", type=Path, help="X2W_DRAW_DUMP_DIR containing pixel_history.txt") + parser.add_argument("--frame", type=int, default=None, help="frame to select") + parser.add_argument("--pixel", type=_parse_pixel, default=None, help="pixel X,Y to select") + parser.add_argument("--baseline-raw", type=_parse_raw, default=None, + help="known pre-draw raw word for the selected format") + parser.add_argument("--max-rows", type=_parse_non_negative, default=DEFAULT_MAX_ROWS, + help=f"maximum timeline rows (default {DEFAULT_MAX_ROWS}, max {MAX_MAX_ROWS})") + args = parser.parse_args(argv) + + if args.max_rows < MIN_MAX_ROWS or args.max_rows > MAX_MAX_ROWS: + print(f"scene_color_report: --max-rows must be between {MIN_MAX_ROWS} and {MAX_MAX_ROWS}", + file=sys.stderr) + return 2 + dump_dir: Path = args.dump_dir + if not dump_dir.is_dir(): + print("scene_color_report: dump directory not found", file=sys.stderr) + return 2 + history_path = dump_dir / HISTORY_FILE + if not history_path.is_file(): + print("scene_color_report: pixel_history.txt not found in the dump directory", file=sys.stderr) + return 2 + + try: + history = parse_history(history_path) + except ReportError as exc: + print(f"scene_color_report: {exc}", file=sys.stderr) + return 2 + except OSError: + print("scene_color_report: pixel_history.txt is not readable", file=sys.stderr) + return 2 + + groups = build_groups(history.samples) + selected, matching_groups = select_group(groups, args.frame, args.pixel) + + if selected is not None: + if args.baseline_raw is not None: + baseline_raw = args.baseline_raw + baseline_sample = None + baseline_supplied = True + else: + baseline_sample = find_baseline(history.samples, selected) + if baseline_sample is not None: + baseline_raw = baseline_sample.raw + baseline_supplied = False + else: + baseline_raw = selected.samples[0].raw + baseline_supplied = False + else: + baseline_sample = None + baseline_raw = 0 + baseline_supplied = args.baseline_raw is not None + + bmps = scan_bmps(dump_dir, selected) + report = format_report( + history=history, + groups=groups, + selected=selected, + baseline_sample=baseline_sample, + baseline_raw=baseline_raw, + baseline_supplied=baseline_supplied, + bmps=bmps, + max_rows=args.max_rows, + requested_frame=args.frame, + requested_pixel=args.pixel, + ) + if selected is not None and matching_groups > 1: + report = report.replace( + "## Classification", + f"_`{matching_groups}` sample groups match the requested frame and pixel; the largest " + "one is shown._\n\n## Classification", + 1, + ) + try: + sys.stdout.reconfigure(encoding="utf-8") + except (AttributeError, OSError): + pass + print(report) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 33bd9f1039ec7ecb4d773ba394d7d8862c619640 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 20:25:53 +0000 Subject: [PATCH 19/44] tooling: report the startup exit code and last presented frame --- docs/experiments/startup-exit-report.md | 50 ++++ docs/startup-runtime.md | 5 + .../python-linux/startup_exit_report.txt | 1 + tests/startup_exit_report_check.py | 125 ++++++++ tools/startup/exit_report.py | 266 ++++++++++++++++++ 5 files changed, 447 insertions(+) create mode 100644 docs/experiments/startup-exit-report.md create mode 100644 tests/checks/python-linux/startup_exit_report.txt create mode 100644 tests/startup_exit_report_check.py create mode 100644 tools/startup/exit_report.py diff --git a/docs/experiments/startup-exit-report.md b/docs/experiments/startup-exit-report.md new file mode 100644 index 0000000000..a080c63ee3 --- /dev/null +++ b/docs/experiments/startup-exit-report.md @@ -0,0 +1,50 @@ +# Startup exit report + +Refs [#870](https://github.com/R0Y00/Xbox2Windows/issues/870). This reader answers a narrower question than +`triage_run.py`: how did one startup run end, and what was the last presented frame? + +## Command + +```powershell +python -B tools/startup/exit_report.py [--json ] +``` + +The directory is the one written by `tools/startup/debug_launch.py` or `tools/startup/run.ps1`. The tool reads +`events.txt`, `finished.txt`, `run.out`, `stderr.txt`, `stdout.txt` and `trap.log` when present. + +## Output + +The Markdown table reports: + +| Item | Source | +|---|---| +| Exit code | `EXIT_PROCESS` in `events.txt`, or `process exited with ...` in `finished.txt` | +| Classification | one of `clean exit`, `nonzero exit`, `exception stop`, `timeout`, `stopped by request`, `missing exit event` | +| End time | the timestamp of the exit, stop, timeout or stop-file record | +| Last present | the highest `x2w-d3d12 heartbeat: N frames presented in T s` sample | +| Last presented surface | the last `x2w-render presented surface` sample | +| First / last exception | only the 32-bit code and first- or second-chance | +| Observed exceptions | count after the loader, single-step, thread-name and debug-output first-chance events are excluded | + +The JSON form contains the same allowlisted fields. It never contains an input path, a module name, a raw +address, an exception parameter or free-form log text. + +## What it proves + +It distinguishes a process that returned 0 from one that returned 1, an exception stop, a timeout and a +stop-file request. It also names the last present sample, so an exit at 307.6 s can be compared with the last +presented frame at 301.8 s without opening the raw logs. + +It does not prove that the exit code came from the title rather than a runtime stub, and it does not identify +the code path that called `ExitProcess`. Those need a debugger breakpoint or a runtime-side hook. The tool is +the bounded receipt; it is not the fix. + +## Tests + +```powershell +python -B tests/startup_exit_report_check.py +``` + +The synthetic check covers a clean exit, a nonzero exit, an exception stop, a timeout, a stop-file request, a +missing exit event, filtered first-chance events, hostile paths and addresses, the highest present sample and +the JSON form. It is listed in `tests/checks/python-linux/startup_exit_report.txt` for the Linux CI job. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 976eb0a8a2..e188dca282 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1258,6 +1258,11 @@ the stop. The report copies only the 32-bit exception code and whether it was fi Check with `python3 -B tests/startup_triage_run_check.py` (ctest `startup_triage_run`). +`tools/startup/exit_report.py` is a narrower reader for the same directory when the question is only how the +process ended. It reports the `EXIT_PROCESS` code, one of six fixed end-state labels, the last present/frame +sample and the last presented surface. It does not copy module names, paths or addresses. Check with +`python3 -B tests/startup_exit_report_check.py`. + ## Iterating on start-up runs This is one way to turn repeated start-up runs into a list of translator work that others can pick up. It combines the tools above (`run.ps1`, `gfx2hlsl.py`, `triage_run.py`) with Windows Sandbox and a logon script that you write yourself; the script is not in this repository. Nothing from a run (executable, package, logs, shaders, captures) is committed or posted. Only instruction names, refusal reasons and counts leave the machine. diff --git a/tests/checks/python-linux/startup_exit_report.txt b/tests/checks/python-linux/startup_exit_report.txt new file mode 100644 index 0000000000..f8c299c41b --- /dev/null +++ b/tests/checks/python-linux/startup_exit_report.txt @@ -0,0 +1 @@ +tests/startup_exit_report_check.py diff --git a/tests/startup_exit_report_check.py b/tests/startup_exit_report_check.py new file mode 100644 index 0000000000..017ccf6723 --- /dev/null +++ b/tests/startup_exit_report_check.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Checks tools/startup/exit_report.py against synthetic debug-launch logs.""" + +from __future__ import annotations + +import json +from pathlib import Path +import sys +import tempfile + + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "tools" / "startup")) +import exit_report # noqa: E402 + + +def report(logs: dict[str, str]) -> tuple[str, exit_report.ExitSummary]: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + for name, text in logs.items(): + (root / name).write_text(text, encoding="utf-8") + summary = exit_report.summarize(root) + return exit_report.format_markdown(summary), summary + + +def expect(report_text: str, summary: exit_report.ExitSummary, want: list[str], label: str) -> None: + for snippet in want: + assert snippet in report_text, f"{label}: missing {snippet!r}\n{report_text}" + assert summary.classification() in { + "clean exit", "nonzero exit", "exception stop", "timeout", "stopped by request", "missing exit event", + }, label + + +def main() -> int: + clean, clean_summary = report({ + "events.txt": " 301.800 exit 0x00000000\n", + "stderr.txt": ( + "x2w-d3d12 heartbeat: 7395 frames presented in 301.8 s (24.53 fps overall)\n" + "x2w-render presented surface 1600x900 format 28, readback 1, mean level 0.0/255\n" + ), + }) + expect(clean, clean_summary, [ + "| Exit code | `0x00000000` (0) |", + "| Classification | clean exit |", + "| End time | `301.8` s |", + "| Last present | `7395` frames at `301.8` s (`24.53` fps overall) |", + "| Last presented surface | `1600x900` format `28`, readback `1`, mean level `0.0/255` |", + ], "clean exit") + + nonzero, nonzero_summary = report({ + "events.txt": " 307.600 exit 0x00000001\n", + }) + expect(nonzero, nonzero_summary, [ + "| Exit code | `0x00000001` (1) |", + "| Classification | nonzero exit |", + "| End time | `307.6` s |", + "| First observed exception | not reported |", + ], "nonzero exit") + + stopped, stopped_summary = report({ + "events.txt": ( + " 250.250 exception 0xE06D7363 C++ exception at C:\\Users\\alice\\game.exe+0x55 first-chance params=['0x1']\n" + " 299.900 exception 0xC0000005 access violation at KERNELBASE.dll+0x9000 second-chance params=['0x0']\n" + "debugger stop 0xc0000005 second-chance\n" + ), + "finished.txt": ( + "stopped at access violation (0xc0000005) at game.exe+0x4da6341 after 253.49 s " + "(second chance) params=['0x1']\n" + ), + }) + expect(stopped, stopped_summary, [ + "| Classification | exception stop |", + "| End time | `253.5` s |", + "| First observed exception | `0xe06d7363` (first-chance) |", + "| Last observed exception | `0xc0000005` (second-chance) |", + "| Observed exceptions | `2` |", + ], "exception stop") + for secret in ("alice", "game.exe", "KERNELBASE", "0x4da6341", "0x55", "0x9000"): + assert secret not in stopped, f"exception stop leaked {secret!r}\n{stopped}" + + timed_out, timeout_summary = report({"finished.txt": "timeout after 300.00 s\n"}) + expect(timed_out, timeout_summary, [ + "| Classification | timeout |", "| End time | `300.0` s |", + ], "timeout") + + requested, requested_summary = report({"finished.txt": "stopped by request after 42.0 s (stop file)\n"}) + expect(requested, requested_summary, ["| Classification | stopped by request |", "| End time | `42.0` s |"], "stop request") + + missing, missing_summary = report({"stderr.txt": "x2w-d3d12 heartbeat: 12 frames presented in 1.0 s (12.0 fps overall)\n"}) + expect(missing, missing_summary, ["| Classification | missing exit event |", "| Last present | `12` frames at `1` s (`12` fps overall) |"], "missing exit") + + filtered, filtered_summary = report({ + "events.txt": ( + " 1.000 exception 0x80000003 breakpoint at ntdll.dll+0x1 first-chance params=[]\n" + " 2.000 exception 0x406d1388 thread name at game.exe+0x2 first-chance params=[]\n" + ), + }) + expect(filtered, filtered_summary, ["| Observed exceptions | `0` |"], "filtered first chance") + assert "0x80000003" not in filtered and "0x406d1388" not in filtered + + hostile, hostile_summary = report({ + "events.txt": ( + " 3.000 exception 0xE06D7363 C++ exception at C:\\Users\\alice\\secret\\game.exe+0x1 second-chance " + "params=['0x00007ff7deadbeef', 'https://acme.example/leak']\n" + " 4.000 exception 0xZZ00ZZ00 junk at X second-chance\n" + ), + "stderr.txt": ( + "x2w-d3d12 heartbeat: 5 frames presented in 2.0 s (2.5 fps overall) acme_widget 0x00007ff7deadbeef\n" + "x2w-render presented surface 1x1 format 28, readback 1, mean level 0.0/255 secret\n" + ), + }) + for needle in ("alice", "secret", "game.exe", "acme", "widget", "deadbeef", "http", "0xZZ00ZZ00"): + assert needle not in hostile, f"hostile input leaked {needle!r}\n{hostile}" + assert hostile_summary.exception_events == 1 + + payload = exit_report.as_json(clean_summary) + assert payload["classification"] == "clean exit" and payload["last_present_frames"] == 7395 + assert json.loads(json.dumps(payload)) == payload + + print("startup_exit_report_check: ok") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/startup/exit_report.py b/tools/startup/exit_report.py new file mode 100644 index 0000000000..a37843543e --- /dev/null +++ b/tools/startup/exit_report.py @@ -0,0 +1,266 @@ +#!/usr/bin/env python3 +"""Summarize how one startup run ended, using the existing debug-launch logs. + +The report is deliberately small: an exit code, one of six fixed end-state +labels, the last present counter and the last presented surface. Input paths, +module names, raw addresses, exception parameters and free-form text are never +copied. The parser accepts the log formats written by +tools/startup/debug_launch.py, tools/startup/run.ps1 and the runtime heartbeats. +""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass, field +import json +from pathlib import Path +import re +import sys +from typing import Iterable + + +LOG_NAMES = ("events.txt", "finished.txt", "run.out", "stderr.txt", "stdout.txt", "trap.log") +MAX_BYTES = 16 * 1024 * 1024 +FILTERED_FIRST_CHANCE = {"0x80000003", "0x80000004", "0x406d1388", "0x40010006"} + +RE_EXIT_EVENT = re.compile(r"^\s*(\d{1,10}(?:\.\d{1,6})?)\s+exit\s+(0x[0-9a-fA-F]{8})\s*$") +RE_EXIT_SUMMARY = re.compile(r"^process exited with (0x[0-9a-fA-F]{8}) after (\d{1,10}(?:\.\d{1,6})?) s$") +RE_STOP_SUMMARY = re.compile( + r"^stopped at [^(]+\((0x[0-9a-fA-F]{8})\) at .+ after (\d{1,10}(?:\.\d{1,6})?) s " + r"\((first|second) chance\)" +) +RE_DEBUGGER_STOP = re.compile(r"^debugger stop (0x[0-9a-fA-F]{8}) (first|second)-chance$") +RE_EXCEPTION = re.compile( + r"^\s*(\d{1,10}(?:\.\d{1,6})?)\s+exception\s+(0x[0-9a-fA-F]{8})\b.*?\b(first|second)-chance\b" +) +RE_TIMEOUT = re.compile(r"^timeout after (\d{1,10}(?:\.\d{1,6})?) s$") +RE_STOP_REQUEST = re.compile(r"^stopped by request after (\d{1,10}(?:\.\d{1,6})?) s \(stop file\)$") +RE_HEARTBEAT = re.compile( + r"x2w-d3d12 heartbeat: (\d{1,10}) frames presented in (\d{1,10}(?:\.\d{1,6})?) s " + r"\((\d{1,10}(?:\.\d{1,6})?) fps overall\)" +) +RE_SURFACE = re.compile( + r"x2w-render presented surface (\d{1,5})x(\d{1,5}) format (\d{1,3}), readback (\d{1,10}), " + r"mean level (\d{1,3}(?:\.\d{1,6})?)/255" +) +RE_CAPTURE = re.compile(r"^present frame (\d{1,10}) surface \S+$") + + +@dataclass +class ExitSummary: + exit_code: str | None = None + end_elapsed_s: float | None = None + timed_out: bool = False + stop_requested: bool = False + confirmed_stop: tuple[str, str] | None = None + first_exception: tuple[str, str] | None = None + last_exception: tuple[str, str] | None = None + exception_events: int = 0 + last_present_frames: int | None = None + last_present_s: float | None = None + last_present_fps: float | None = None + last_surface: tuple[int, int, int, int, str] | None = None + last_capture_frame: int | None = None + lines_scanned: int = 0 + + def classification(self) -> str: + if self.confirmed_stop is not None: + return "exception stop" + if self.timed_out: + return "timeout" + if self.stop_requested: + return "stopped by request" + if self.exit_code is not None: + return "clean exit" if self.exit_code == "0x00000000" else "nonzero exit" + return "missing exit event" + + def observe(self, line: str) -> None: + self.lines_scanned += 1 + match = RE_HEARTBEAT.search(line) + if match: + elapsed = float(match.group(2)) + if self.last_present_s is None or elapsed >= self.last_present_s: + self.last_present_frames = int(match.group(1)) + self.last_present_s = elapsed + self.last_present_fps = float(match.group(3)) + return + match = RE_SURFACE.search(line) + if match: + self.last_surface = ( + int(match.group(1)), int(match.group(2)), int(match.group(3)), + int(match.group(4)), match.group(5), + ) + return + match = RE_CAPTURE.match(line) + if match: + self.last_capture_frame = int(match.group(1)) + return + match = RE_EXIT_EVENT.match(line) + if match: + self.exit_code = match.group(2).lower() + self.end_elapsed_s = float(match.group(1)) + return + match = RE_EXIT_SUMMARY.match(line) + if match: + self.exit_code = match.group(1).lower() + self.end_elapsed_s = float(match.group(2)) + return + match = RE_TIMEOUT.match(line) + if match: + self.timed_out = True + self.end_elapsed_s = float(match.group(1)) + return + match = RE_STOP_REQUEST.match(line) + if match: + self.stop_requested = True + self.end_elapsed_s = float(match.group(1)) + return + match = RE_DEBUGGER_STOP.match(line) + if match: + self.confirmed_stop = (match.group(1).lower(), match.group(2)) + return + match = RE_STOP_SUMMARY.match(line) + if match: + self.confirmed_stop = (match.group(1).lower(), match.group(3)) + self.end_elapsed_s = float(match.group(2)) + return + match = RE_EXCEPTION.match(line) + if match and (match.group(3) == "second" or match.group(2).lower() not in FILTERED_FIRST_CHANCE): + exception = (match.group(2).lower(), match.group(3)) + self.exception_events += 1 + if self.first_exception is None: + self.first_exception = exception + self.last_exception = exception + + +def _read_logs(root: Path) -> tuple[list[str], list[str]]: + lines: list[str] = [] + names: list[str] = [] + for name in LOG_NAMES: + path = root / name + if not path.is_file(): + continue + try: + data = path.read_bytes()[:MAX_BYTES] + except OSError: + continue + names.append(name) + lines.extend(data.decode("utf-8", errors="replace").splitlines()) + return names, lines + + +def summarize(root: Path) -> ExitSummary: + names, lines = _read_logs(root) + summary = ExitSummary() + # finished.txt is authoritative for the final state; parse it before the other logs so an + # earlier duplicate event cannot overwrite a later exit code. + for name in ("finished.txt", "run.out"): + path = root / name + if path.is_file(): + try: + for line in path.read_text(encoding="utf-8", errors="replace").splitlines(): + summary.observe(line) + except OSError: + pass + for name in names: + if name in ("finished.txt", "run.out"): + continue + path = root / name + try: + for line in path.read_text(encoding="utf-8", errors="replace").splitlines(): + summary.observe(line) + except OSError: + pass + return summary + + +def _exception_text(exception: tuple[str, str] | None) -> str: + return "not reported" if exception is None else f"`{exception[0]}` ({exception[1]}-chance)" + + +def _exit_text(code: str | None) -> str: + return "not reported" if code is None else f"`{code}` ({int(code, 16)})" + + +def _time_text(value: float | None) -> str: + return "not reported" if value is None else f"`{value:.1f}` s" + + +def _present_text(summary: ExitSummary) -> str: + if summary.last_present_frames is not None and summary.last_present_s is not None: + fps = "" if summary.last_present_fps is None else f" (`{summary.last_present_fps:g}` fps overall)" + return f"`{summary.last_present_frames}` frames at `{summary.last_present_s:g}` s{fps}" + if summary.last_capture_frame is not None: + return f"capture frame `{summary.last_capture_frame}`" + return "not reported" + + +def _surface_text(summary: ExitSummary) -> str: + if summary.last_surface is None: + return "not reported" + width, height, format_code, readback, mean = summary.last_surface + return f"`{width}x{height}` format `{format_code}`, readback `{readback}`, mean level `{mean}/255`" + + +def format_markdown(summary: ExitSummary) -> str: + return "\n".join([ + "## Startup Exit Summary", + "", + "| Item | Value |", + "| --- | --- |", + f"| Exit code | {_exit_text(summary.exit_code)} |", + f"| Classification | {summary.classification()} |", + f"| End time | {_time_text(summary.end_elapsed_s)} |", + f"| Last present | {_present_text(summary)} |", + f"| Last presented surface | {_surface_text(summary)} |", + f"| First observed exception | {_exception_text(summary.first_exception)} |", + f"| Last observed exception | {_exception_text(summary.last_exception)} |", + f"| Observed exceptions | `{summary.exception_events}` |", + "", + ]) + + +def as_json(summary: ExitSummary) -> dict[str, object]: + return { + "exit_code": summary.exit_code, + "classification": summary.classification(), + "end_elapsed_s": summary.end_elapsed_s, + "last_present_frames": summary.last_present_frames, + "last_present_s": summary.last_present_s, + "last_present_fps": summary.last_present_fps, + "last_surface": None if summary.last_surface is None else { + "width": summary.last_surface[0], + "height": summary.last_surface[1], + "format": summary.last_surface[2], + "readback": summary.last_surface[3], + "mean_level": summary.last_surface[4], + }, + "first_exception": None if summary.first_exception is None else { + "code": summary.first_exception[0], "chance": summary.first_exception[1], + }, + "last_exception": None if summary.last_exception is None else { + "code": summary.last_exception[0], "chance": summary.last_exception[1], + }, + "exception_events": summary.exception_events, + "lines_scanned": summary.lines_scanned, + } + + +def main(argv: Iterable[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Summarize how one startup run ended without copying private text.") + parser.add_argument("logdir", type=Path, help="directory written by debug_launch.py or run.ps1") + parser.add_argument("--json", type=Path, help="also write the allowlisted fields as JSON") + args = parser.parse_args(list(argv) if argv is not None else None) + if not args.logdir.is_dir(): + print(f"exit_report: not a directory: {args.logdir}", file=sys.stderr) + return 2 + summary = summarize(args.logdir) + print(format_markdown(summary)) + if args.json: + args.json.parent.mkdir(parents=True, exist_ok=True) + args.json.write_text(json.dumps(as_json(summary), indent=2, sort_keys=True) + "\n", encoding="utf-8") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 8f7953f226a1d46316b4a42a4c899d65be4d37d0 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 20:29:57 +0000 Subject: [PATCH 20/44] runtime: count decoded Opus completions and desktop audio submissions --- CMakeLists.txt | 11 + .../startup-opus-completion-count.md | 64 +++ docs/startup-runtime.md | 10 +- src/startup_stubs/audio_sink.cpp | 21 +- src/startup_stubs/audio_sink.h | 3 +- src/startup_stubs/audio_telemetry.h | 97 +++++ src/startup_stubs/xapu.cpp | 130 ++++++- tests/startup_audio_output.cpp | 18 +- tests/startup_xapu_opus_count_check.cpp | 364 ++++++++++++++++++ 9 files changed, 698 insertions(+), 20 deletions(-) create mode 100644 docs/experiments/startup-opus-completion-count.md create mode 100644 src/startup_stubs/audio_telemetry.h create mode 100644 tests/startup_xapu_opus_count_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 7c838ba024..57da7e2c0d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1012,6 +1012,17 @@ if(X2W_WITH_OPUS) add_dependencies(startup_xapu_opus_check startup_stub_xapu) add_test(NAME startup_xapu_opus COMMAND startup_xapu_opus_check "$") set_tests_properties(startup_xapu_opus PROPERTIES TIMEOUT 60) + + # Bounded telemetry for the same optional decode path: decoded packets, dequeued completions and + # refusals by reason. Generates its tones with libopus; no captured packet is stored. + add_executable(startup_xapu_opus_count_check tests/startup_xapu_opus_count_check.cpp) + target_compile_features(startup_xapu_opus_count_check PRIVATE cxx_std_17) + target_include_directories(startup_xapu_opus_count_check PRIVATE src) + target_link_libraries(startup_xapu_opus_count_check PRIVATE Opus::opus) + set_target_properties(startup_xapu_opus_count_check PROPERTIES MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + add_dependencies(startup_xapu_opus_count_check startup_stub_xapu) + add_test(NAME startup_xapu_opus_count COMMAND startup_xapu_opus_count_check "$") + set_tests_properties(startup_xapu_opus_count PROPERTIES TIMEOUT 60) endif() add_executable(startup_chad_check tests/startup_chad_check.cpp) diff --git a/docs/experiments/startup-opus-completion-count.md b/docs/experiments/startup-opus-completion-count.md new file mode 100644 index 0000000000..caa0b55aa5 --- /dev/null +++ b/docs/experiments/startup-opus-completion-count.md @@ -0,0 +1,64 @@ +# Startup Opus completion counters + +Refs [#1145](https://github.com/R0Y00/Xbox2Windows/issues/1145) and +[#870](https://github.com/R0Y00/Xbox2Windows/issues/870). This note covers the optional Opus +decode path built with `-DX2W_WITH_OPUS=ON` and `X2W_XAPU_TYPED_COMPLETIONS=1`. + +## What is counted + +`xapu.dll` keeps process-wide saturating counters for: + +| Counter | Meaning | +|---|---| +| `type3` | readable type 3 commands seen while typed completions are on | +| `packets` | commands libopus decoded successfully | +| `completions` | type 3 results dequeued by the caller | +| `refusals` | sum of the refusal counters below | +| `invalid_argument` | a field or output range failed before libopus | +| `opus_error` | libopus rejected the packet | +| `capacity` | libopus reported `OPUS_BUFFER_TOO_SMALL` | +| `queue_full` | the per-connection queue was full | +| `short_command` | the decode fields crossed the readable header | +| `unknown_handle` | the command named a handle that was not connected | +| `out_of_memory` | a new decoder could not be created | +| `header` | the command header was null or unreadable | + +The counters start on the first readable type 3 command. A run with typed completions off reads +and writes nothing here. + +The audio sink also reports `accepted` and `not_open` submissions, so a run can distinguish an +endpoint that never opened from one that accepted decoded blocks. + +## Summary line + +At the last `XApuDisconnect`, and from `atexit` when a run never disconnects, the stand-in writes +one stable line when the counters moved since the previous summary: + +```text +x2w-audio XApu opus summary: type3=8 packets=2 completions=2 refusals=7 invalid_argument=1 opus_error=1 capacity=1 queue_full=1 short_command=1 unknown_handle=1 out_of_memory=0 header=1 +``` + +The line is written to stderr and to `X2W_TRAP_LOG`, like the other audio lines. It is a snapshot; +two threads can move different fields between their loads. Each field is exact on its own. + +## Test + +```powershell +cmake --preset dev -DX2W_WITH_OPUS=ON -DOpus_DIR=/lib/cmake/Opus +cmake --build --preset dev --target startup_stub_xapu startup_xapu_opus_count_check +ctest --preset dev --no-tests=error -R '^startup_xapu_opus_count$' -V +``` + +The fixture encodes synthetic 1 kHz tones with libopus and drives the real stand-in exports. It +checks two successful decodes and dequeues, a malformed packet, insufficient capacity, an invalid +rate, a short command, an unknown handle, a full queue, a null header, saturation at +`UINT64_MAX`, one summary after the last disconnect, and that typed completions off neither +decode nor add a summary line. It passed in Debug with libopus 1.5.2 on Windows 11 build 26300. + +## Limits + +The counters prove that the optional decode path ran and that the caller consumed the results. +They do not prove that the output was audible, that the desktop sink accepted the same block, or +that XMA/AcpHal works. The `startup_audio_output` fixture covers the sink's accepted/not-open +counters separately. The title run that produced the 27/11 audio observation was not available +locally, so this change adds the measurement, not the run receipt. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 976eb0a8a2..77e565d3d1 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -2962,8 +2962,8 @@ are copied from scratch only after the result is queued. ```powershell cmake --preset dev -DX2W_WITH_OPUS=ON -DOpus_DIR=/lib/cmake/Opus -cmake --build --preset dev --target startup_stub_xapu startup_xapu_queue_check startup_xapu_opus_check -ctest --preset dev --no-tests=error -R '^startup_xapu_(queue|opus)$' -V +cmake --build --preset dev --target startup_stub_xapu startup_xapu_queue_check startup_xapu_opus_check startup_xapu_opus_count_check +ctest --preset dev --no-tests=error -R '^startup_xapu_(queue|opus|opus_count)$' -V ``` `startup_xapu_opus` encodes generated 1 kHz tones with the same libopus and checks exact byte counts (3840 for @@ -2973,6 +2973,12 @@ an untouched output and an empty queue, a full queue that leaves the slot's stre starting a fresh decoder, a rate change on a live slot, and that type `3` decodes nothing with typed completions off. It is registered only in the optional build. +`startup_xapu_opus_count` uses the same libopus tones to check the bounded telemetry: decoded +packets, dequeued completions and each refusal reason. The stand-in writes one +`x2w-audio XApu opus summary:` line at the last disconnect or at process exit, and the audio sink +reports `accepted` and `not_open` submissions. See +[the completion-count note](experiments/startup-opus-completion-count.md). + `src/startup_stubs/audio_sink.{h,cpp}` is a desktop WASAPI shared-mode render sink. It opens the default render endpoint, takes the mix format from `GetMixFormat` (32-bit float or 16-bit PCM only), converts each submitted block (format, frame count, bytes) to it, and writes it through diff --git a/src/startup_stubs/audio_sink.cpp b/src/startup_stubs/audio_sink.cpp index 635f10040e..d8f1ca8671 100644 --- a/src/startup_stubs/audio_sink.cpp +++ b/src/startup_stubs/audio_sink.cpp @@ -124,7 +124,10 @@ void AudioSink::observe(bool withholding) Submit AudioSink::submit(const BlockFormat& in, uint32_t frames, const void* bytes) { const uint32_t call = calls_++; - if (!p_) return Submit::NotOpen; + if (!p_) { + ++r_.not_open; + return Submit::NotOpen; + } ResampleState trial = resample_; // committed only once the block is accepted if (!convert_block(in, bytes, frames, mix_, conv_buf_, &trial)) { ++r_.unsupported; @@ -132,7 +135,10 @@ Submit AudioSink::submit(const BlockFormat& in, uint32_t frames, const void* byt } const uint32_t out_frames = static_cast(conv_buf_.size() / mix_.frame_bytes()); const uint32_t pad = padding(); - if (pad == padding_failed) return Submit::NotOpen; + if (pad == padding_failed) { + ++r_.not_open; + return Submit::NotOpen; + } if (out_frames > buffer_frames_ - pad) { ++r_.rejected_full; return Submit::Full; @@ -141,9 +147,15 @@ Submit AudioSink::submit(const BlockFormat& in, uint32_t frames, const void* byt if (timer_.drained_start >= 0) timer_.resume(now_ms(), r_.consumed_frames); // the producer is back if (out_frames > 0) { BYTE* dst = nullptr; - if (FAILED(p_->render->GetBuffer(out_frames, &dst)) || !dst) return Submit::NotOpen; + if (FAILED(p_->render->GetBuffer(out_frames, &dst)) || !dst) { + ++r_.not_open; + return Submit::NotOpen; + } std::memcpy(dst, conv_buf_.data(), conv_buf_.size()); - if (FAILED(p_->render->ReleaseBuffer(out_frames, 0))) return Submit::NotOpen; + if (FAILED(p_->render->ReleaseBuffer(out_frames, 0))) { + ++r_.not_open; + return Submit::NotOpen; + } } resample_ = std::move(trial); if (r_.first_block < 0) { @@ -153,6 +165,7 @@ Submit AudioSink::submit(const BlockFormat& in, uint32_t frames, const void* byt r_.frames.push_back(out_frames); r_.peaks.push_back(block_peak(in, bytes, frames)); r_.submitted_frames += out_frames; + ++r_.accepted; if (!started_ && SUCCEEDED(p_->client->Start())) started_ = true; return Submit::Accepted; } diff --git a/src/startup_stubs/audio_sink.h b/src/startup_stubs/audio_sink.h index c55ffbf768..f00edbca1b 100644 --- a/src/startup_stubs/audio_sink.h +++ b/src/startup_stubs/audio_sink.h @@ -259,7 +259,8 @@ struct Report { uint64_t submitted_frames = 0; // frames written to the endpoint uint64_t consumed_frames = 0; // submitted frames minus frames still queued uint64_t clock_frames = 0; // IAudioClock position converted to frames - uint32_t unsupported = 0, rejected_full = 0; + uint64_t accepted = 0; // submit() calls that returned Submit::Accepted + uint32_t unsupported = 0, rejected_full = 0, not_open = 0; uint32_t padding_errors = 0; // GetCurrentPadding failed (e.g. the endpoint went away): not a measurement double drained_ms = 0, recovery_ms = -1; // recovery_ms < 0: not measured // Glitches: the render API exposes no discontinuity flag, so this stays "not available". diff --git a/src/startup_stubs/audio_telemetry.h b/src/startup_stubs/audio_telemetry.h new file mode 100644 index 0000000000..e7f9b3a671 --- /dev/null +++ b/src/startup_stubs/audio_telemetry.h @@ -0,0 +1,97 @@ +// Experimental (docs/startup-runtime.md): bounded counters for the optional Opus decode path. +// +// Every counter saturates at UINT64_MAX instead of wrapping. The values are process-wide and are +// read without a single coherent snapshot: a summary taken while another thread enqueues can show +// one field from before that enqueue and another from after it. Each field is exact on its own. +#pragma once + +#include +#include +#include + +namespace x2w_audio { + +inline void saturating_add(std::atomic& counter, std::uint64_t amount = 1) noexcept +{ + std::uint64_t seen = counter.load(std::memory_order_relaxed); + for (;;) { + const std::uint64_t next = amount > (std::numeric_limits::max)() - seen + ? (std::numeric_limits::max)() + : seen + amount; + if (next == seen || counter.compare_exchange_weak(seen, next, std::memory_order_relaxed, + std::memory_order_relaxed)) + return; + } +} + +// Counters for one process's type-3 Opus path. `type3_commands` counts every readable type-3 +// command while typed completions are on. `packets_decoded` counts calls libopus accepted with a +// non-empty packet. `decoded_completions` counts type-3 results dequeued by the caller, so a packet +// that decodes but is never consumed is not in it. The refusal fields name the first check that +// refused the command; `header` covers a null or unreadable XApuEnqueueCommand header. +struct OpusCounters { + std::atomic type3_commands{0}; + std::atomic packets_decoded{0}; + std::atomic decoded_completions{0}; + std::atomic refused_header{0}; + std::atomic refused_short_command{0}; + std::atomic refused_unknown_handle{0}; + std::atomic refused_queue_full{0}; + std::atomic refused_invalid_argument{0}; + std::atomic refused_opus_error{0}; + std::atomic refused_capacity{0}; + std::atomic refused_out_of_memory{0}; +}; + +struct OpusCounterSnapshot { + std::uint64_t type3_commands = 0; + std::uint64_t packets_decoded = 0; + std::uint64_t decoded_completions = 0; + std::uint64_t refused_header = 0; + std::uint64_t refused_short_command = 0; + std::uint64_t refused_unknown_handle = 0; + std::uint64_t refused_queue_full = 0; + std::uint64_t refused_invalid_argument = 0; + std::uint64_t refused_opus_error = 0; + std::uint64_t refused_capacity = 0; + std::uint64_t refused_out_of_memory = 0; +}; + +inline OpusCounterSnapshot snapshot(const OpusCounters& counters) noexcept +{ + return {counters.type3_commands.load(std::memory_order_relaxed), + counters.packets_decoded.load(std::memory_order_relaxed), + counters.decoded_completions.load(std::memory_order_relaxed), + counters.refused_header.load(std::memory_order_relaxed), + counters.refused_short_command.load(std::memory_order_relaxed), + counters.refused_unknown_handle.load(std::memory_order_relaxed), + counters.refused_queue_full.load(std::memory_order_relaxed), + counters.refused_invalid_argument.load(std::memory_order_relaxed), + counters.refused_opus_error.load(std::memory_order_relaxed), + counters.refused_capacity.load(std::memory_order_relaxed), + counters.refused_out_of_memory.load(std::memory_order_relaxed)}; +} + +inline std::uint64_t saturating_total(std::uint64_t& total, std::uint64_t value) noexcept +{ + total = value > (std::numeric_limits::max)() - total + ? (std::numeric_limits::max)() + : total + value; + return total; +} + +inline std::uint64_t refused_total(const OpusCounterSnapshot& s) noexcept +{ + std::uint64_t total = 0; + saturating_total(total, s.refused_header); + saturating_total(total, s.refused_short_command); + saturating_total(total, s.refused_unknown_handle); + saturating_total(total, s.refused_queue_full); + saturating_total(total, s.refused_invalid_argument); + saturating_total(total, s.refused_opus_error); + saturating_total(total, s.refused_capacity); + saturating_total(total, s.refused_out_of_memory); + return total; +} + +} // namespace x2w_audio diff --git a/src/startup_stubs/xapu.cpp b/src/startup_stubs/xapu.cpp index d3cbc51986..eee7ff171b 100644 --- a/src/startup_stubs/xapu.cpp +++ b/src/startup_stubs/xapu.cpp @@ -4,7 +4,9 @@ #define X2W_TRAP_MODULE_ID 3 #include "startup_stubs/trap.h" #include "startup_stubs/local_log.h" +#include "startup_stubs/audio_telemetry.h" #include +#include #include #include #ifdef X2W_HAVE_OPUS @@ -27,6 +29,8 @@ // bytes (frames * channels * 4), +0x38 output pointer (interleaved float). Type 2 frees the slot's // decoder and type 5 resets it. A command with no packet (null pointer, 0 bytes) completes with 0 bytes. // A refused decode returns an error, queues nothing and leaves the output untouched. +// The same build keeps bounded counters for decoded packets, dequeued decoded completions and +// refusals by reason, and writes one stable summary at the last disconnect and at process exit. namespace { using u64 = std::uint64_t; constexpr long hr_ok = 0; @@ -48,6 +52,9 @@ struct QueueEntry { std::uint32_t type = 0; std::uint32_t slot = 0; std::uint32_t value = 0; // typed result +0x34: decoded bytes of a type 3 command +#ifdef X2W_HAVE_OPUS + bool decoded = false; // this result came from a successful libopus call +#endif }; #ifdef X2W_HAVE_OPUS @@ -80,6 +87,64 @@ Connection* connections = nullptr; u64 next_handle = 0x5841500000000001ULL; bool timer_active = false; +#ifdef X2W_HAVE_OPUS +// Telemetry for the optional decode path. It starts with the first readable type-3 command, so a +// default run with typed completions off reads and writes nothing here. +x2w_audio::OpusCounters opus_counts; +std::atomic opus_counters_on{false}; +SRWLOCK opus_summary_lock = SRWLOCK_INIT; +x2w_audio::OpusCounterSnapshot reported_opus_counts{}; + +bool same_opus_counts(const x2w_audio::OpusCounterSnapshot& a, const x2w_audio::OpusCounterSnapshot& b) noexcept +{ + return a.type3_commands == b.type3_commands && a.packets_decoded == b.packets_decoded && + a.decoded_completions == b.decoded_completions && a.refused_header == b.refused_header && + a.refused_short_command == b.refused_short_command && + a.refused_unknown_handle == b.refused_unknown_handle && + a.refused_queue_full == b.refused_queue_full && + a.refused_invalid_argument == b.refused_invalid_argument && + a.refused_opus_error == b.refused_opus_error && a.refused_capacity == b.refused_capacity && + a.refused_out_of_memory == b.refused_out_of_memory; +} + +// Writes the totals since the previous summary, when they moved. Called at the last disconnect and +// from atexit, so a run that never disconnects still ends with one line on stderr and X2W_TRAP_LOG. +void log_opus_summary() noexcept +{ + if (!opus_counters_on.load(std::memory_order_relaxed)) return; + const x2w_audio::OpusCounterSnapshot now = x2w_audio::snapshot(opus_counts); + AcquireSRWLockExclusive(&opus_summary_lock); + const bool changed = !same_opus_counts(now, reported_opus_counts); + if (changed) reported_opus_counts = now; + ReleaseSRWLockExclusive(&opus_summary_lock); + if (!changed || (!now.type3_commands && !x2w_audio::refused_total(now))) return; + x2w_local::logf("x2w-audio XApu opus summary: type3=%llu packets=%llu completions=%llu refusals=%llu " + "invalid_argument=%llu opus_error=%llu capacity=%llu queue_full=%llu short_command=%llu " + "unknown_handle=%llu out_of_memory=%llu header=%llu", + static_cast(now.type3_commands), + static_cast(now.packets_decoded), + static_cast(now.decoded_completions), + static_cast(x2w_audio::refused_total(now)), + static_cast(now.refused_invalid_argument), + static_cast(now.refused_opus_error), + static_cast(now.refused_capacity), + static_cast(now.refused_queue_full), + static_cast(now.refused_short_command), + static_cast(now.refused_unknown_handle), + static_cast(now.refused_out_of_memory), + static_cast(now.refused_header)); +} + +void start_opus_counters() noexcept +{ + bool expected = false; + if (!opus_counters_on.compare_exchange_strong(expected, true, std::memory_order_relaxed)) return; + std::atexit(log_opus_summary); +} + +enum class DecodeRefusal { none, invalid_argument, opus_error, capacity, out_of_memory }; +#endif + // Makes room for one more entry, so a following place_result cannot fail. bool reserve_result(Connection& conn) noexcept { @@ -157,11 +222,15 @@ void drop_decoder(Connection& conn, std::uint32_t slot, bool destroy) noexcept } // Decodes the packet of a type 3 command into a scratch buffer, so a refusal never touches the -// caller's output. On S_OK, *pcm holds `bytes` of interleaved float for *dest. Called with -// connection_lock held, which also guards the scratch buffer. -long decode_packet(Connection& conn, const unsigned char* c, std::uint32_t& bytes, const float** pcm, void** dest) noexcept +// caller's output. On S_OK, *pcm holds `bytes` of interleaved float for *dest. `decoded_packet` +// distinguishes a libopus decode from the no-packet completion, and `refusal` names the first check +// that refused the command. Called with connection_lock held, which also guards the scratch buffer. +long decode_packet(Connection& conn, const unsigned char* c, std::uint32_t& bytes, const float** pcm, void** dest, + bool& decoded_packet, DecodeRefusal& refusal) noexcept { static float scratch[max_frames * 2]; + decoded_packet = false; + refusal = DecodeRefusal::none; std::uint32_t slot = 0, frames = 0, packet_bytes = 0, out_bytes = 0; float rate_f = 0; u64 packet = 0, out = 0; @@ -181,8 +250,10 @@ long decode_packet(Connection& conn, const unsigned char* c, std::uint32_t& byte const std::uint32_t channels = frames && frames <= max_frames && out_bytes % (frames * 4) == 0 ? out_bytes / (frames * 4) : 0; if (slot >= max_slots || !rate || (channels != 1 && channels != 2) || packet_bytes == 0 || packet_bytes > max_packet_bytes || !x2w_local::readable(reinterpret_cast(packet), packet_bytes) || - !x2w_local::writable(reinterpret_cast(out), out_bytes)) + !x2w_local::writable(reinterpret_cast(out), out_bytes)) { + refusal = DecodeRefusal::invalid_argument; return hr_invalid_arg; + } // A new rate or channel count gets a new decoder, which replaces the slot's only after a good decode. SlotDecoder& d = conn.decoders[slot]; OpusDecoder* decoder = d.decoder; @@ -192,6 +263,7 @@ long decode_packet(Connection& conn, const unsigned char* c, std::uint32_t& byte decoder = opus_decoder_create(rate, static_cast(channels), &error); if (!decoder || error != OPUS_OK) { if (decoder) opus_decoder_destroy(decoder); + refusal = DecodeRefusal::out_of_memory; return hr_out_of_memory; } } @@ -199,6 +271,7 @@ long decode_packet(Connection& conn, const unsigned char* c, std::uint32_t& byte static_cast(packet_bytes), scratch, static_cast(frames), 0); if (decoded < 0) { if (fresh) opus_decoder_destroy(decoder); + refusal = decoded == OPUS_BUFFER_TOO_SMALL ? DecodeRefusal::capacity : DecodeRefusal::opus_error; static LONG errors; if (x2w_local::first_calls(errors, 8)) x2w_local::logf("x2w-audio XApu decode slot=%u bytes=%u -> opus error %d", slot, packet_bytes, decoded); @@ -209,6 +282,7 @@ long decode_packet(Connection& conn, const unsigned char* c, std::uint32_t& byte d = SlotDecoder{decoder, static_cast(channels), rate}; } bytes = static_cast(decoded) * channels * 4u; + decoded_packet = true; *pcm = scratch; *dest = reinterpret_cast(out); return hr_ok; @@ -296,6 +370,10 @@ extern "C" __declspec(noinline) long XApuDequeueResult(u64 rcx, u64 rdx, u64 r8, if (conn->count > 0) { entry = pop_result(*conn); hr = hr_ok; +#ifdef X2W_HAVE_OPUS + if (entry.decoded && typed_completions()) + x2w_audio::saturating_add(opus_counts.decoded_completions); +#endif } else { hr = hr_pending_results; } @@ -321,6 +399,12 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 if (!permissive()) x2w_trap::fire(X2W_TRAP_MODULE, X2W_TRAP_MODULE_ID, "XApuEnqueueCommand", 3, rcx, rdx, r8, r9, _ReturnAddress()); if (!rdx || !x2w_local::readable(reinterpret_cast(rdx), command_header_size)) { +#ifdef X2W_HAVE_OPUS + if (typed_completions()) { + start_opus_counters(); + x2w_audio::saturating_add(opus_counts.refused_header); + } +#endif static LONG bad_cmd_calls; if (x2w_local::first_calls(bad_cmd_calls, 2)) x2w_local::logf("x2w-audio XApuEnqueueCommand handle=0x%llx -> E_POINTER", rcx); @@ -331,7 +415,15 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 std::memcpy(&entry.slot, reinterpret_cast(rdx) + 4, sizeof(entry.slot)); #ifdef X2W_HAVE_OPUS const bool decode = entry.type == 3 && typed_completions(); + DecodeRefusal refusal = DecodeRefusal::none; + bool decoded_packet = false; + bool queue_refused = false; + if (decode) { + start_opus_counters(); + x2w_audio::saturating_add(opus_counts.type3_commands); + } if (decode && !x2w_local::readable(reinterpret_cast(rdx), decode_command_size)) { + x2w_audio::saturating_add(opus_counts.refused_short_command); x2w_local::logf("x2w-audio XApuEnqueueCommand handle=0x%llx short decode command -> E_POINTER", rcx); return hr_pointer; } @@ -345,12 +437,18 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 void* dest = nullptr; // Refuse a full queue before touching any decoder state. hr = reserve_result(*conn) ? hr_ok : hr_out_of_memory; + queue_refused = hr != hr_ok; if (hr == hr_ok && decode) { - hr = decode_packet(*conn, reinterpret_cast(rdx), entry.value, &pcm, &dest); + hr = decode_packet(*conn, reinterpret_cast(rdx), entry.value, &pcm, &dest, + decoded_packet, refusal); } else if (hr == hr_ok && (entry.type == 2 || entry.type == 5)) { drop_decoder(*conn, entry.slot, entry.type == 2); } if (hr == hr_ok) { + if (decode) { + entry.decoded = decoded_packet; + if (decoded_packet) x2w_audio::saturating_add(opus_counts.packets_decoded); + } place_result(*conn, entry); if (pcm) std::memcpy(dest, pcm, entry.value); } @@ -359,6 +457,22 @@ extern "C" __declspec(noinline) long XApuEnqueueCommand(u64 rcx, u64 rdx, u64 r8 #endif } ReleaseSRWLockExclusive(&connection_lock); +#ifdef X2W_HAVE_OPUS + if (decode && hr != hr_ok) { + if (!conn) + x2w_audio::saturating_add(opus_counts.refused_unknown_handle); + else if (queue_refused) + x2w_audio::saturating_add(opus_counts.refused_queue_full); + else if (refusal == DecodeRefusal::invalid_argument) + x2w_audio::saturating_add(opus_counts.refused_invalid_argument); + else if (refusal == DecodeRefusal::opus_error) + x2w_audio::saturating_add(opus_counts.refused_opus_error); + else if (refusal == DecodeRefusal::capacity) + x2w_audio::saturating_add(opus_counts.refused_capacity); + else if (refusal == DecodeRefusal::out_of_memory) + x2w_audio::saturating_add(opus_counts.refused_out_of_memory); + } +#endif static LONG calls; if (x2w_local::first_calls(calls, 24)) { char command[3 * 0x60 + 1]; @@ -379,6 +493,9 @@ extern "C" __declspec(noinline) long XApuDisconnect(u64 rcx, u64 rdx, u64 r8, u6 while (*slot && (*slot)->handle != rcx) slot = &(*slot)->next; Connection* conn = *slot; if (conn) *slot = conn->next; +#ifdef X2W_HAVE_OPUS + const bool last_connection = conn && !connections; +#endif if (conn && !connections && timer_active) { timeEndPeriod(1); timer_active = false; @@ -395,5 +512,8 @@ extern "C" __declspec(noinline) long XApuDisconnect(u64 rcx, u64 rdx, u64 r8, u6 delete[] conn->entries; delete conn; x2w_local::logf("x2w-audio XApuDisconnect handle=0x%llx -> S_OK", rcx); +#ifdef X2W_HAVE_OPUS + if (last_connection) log_opus_summary(); +#endif return hr_ok; } diff --git a/tests/startup_audio_output.cpp b/tests/startup_audio_output.cpp index d95dc1953d..bdb8af0554 100644 --- a/tests/startup_audio_output.cpp +++ b/tests/startup_audio_output.cpp @@ -24,11 +24,12 @@ int fail(const char* what, int code) void print_report(const char* name, const Report& r) { - std::printf("%s: first_block=%lld submitted_blocks=%zu submitted_frames=%llu consumed_frames=%llu clock_frames=%llu " - "unsupported=%u rejected_full=%u padding_errors=%u drained_ms=%.1f recovery_ms=%.1f glitches=%s\n", - name, static_cast(r.first_block), r.frames.size(), static_cast(r.submitted_frames), - static_cast(r.consumed_frames), static_cast(r.clock_frames), - r.unsupported, r.rejected_full, r.padding_errors, r.drained_ms, r.recovery_ms, r.glitches_available ? "reported" : "not available"); + std::printf("%s: first_block=%lld submitted_blocks=%zu accepted=%llu submitted_frames=%llu consumed_frames=%llu clock_frames=%llu " + "unsupported=%u rejected_full=%u not_open=%u padding_errors=%u drained_ms=%.1f recovery_ms=%.1f glitches=%s\n", + name, static_cast(r.first_block), r.frames.size(), static_cast(r.accepted), + static_cast(r.submitted_frames), static_cast(r.consumed_frames), + static_cast(r.clock_frames), r.unsupported, r.rejected_full, r.not_open, + r.padding_errors, r.drained_ms, r.recovery_ms, r.glitches_available ? "reported" : "not available"); } // Polls until done() holds or ms elapse; every wait in this fixture goes through here. @@ -87,7 +88,7 @@ int run() wait_for(a, 300, [] { return false; }); const Report ra = a.report(); print_report("case a (no submission)", ra); - if (ra.first_block != -1 || !ra.frames.empty() || ra.submitted_frames != 0 || ra.consumed_frames != 0) + if (ra.first_block != -1 || !ra.frames.empty() || ra.accepted != 0 || ra.submitted_frames != 0 || ra.consumed_frames != 0) return fail("case a reported accepted or consumed frames without a submission", 1); // (b) Continuous stream of eight distinguishable 40 ms blocks; block 3 is all zeros. @@ -104,7 +105,7 @@ int run() wait_for(b, 3000, [&] { return b.report().consumed_frames == 8ull * block; }); const Report rb = b.report(); print_report("case b (continuous with silence)", rb); - if (rb.first_block != 0 || rb.frames.size() != 8 || rb.submitted_frames != 8ull * block) return fail("case b submitted counts", 3); + if (rb.first_block != 0 || rb.frames.size() != 8 || rb.accepted != 8 || rb.submitted_frames != 8ull * block) return fail("case b submitted counts", 3); for (const uint32_t f : rb.frames) if (f != block) return fail("case b block frame count", 3); if (rb.consumed_frames != rb.submitted_frames) return fail("case b consumption incomplete", 4); if (rb.peaks[3] != 0.0f) return fail("case b silent block was not silent", 5); @@ -128,6 +129,7 @@ int run() wait_for(c, 3000, [&] { return c.report().recovery_ms >= 0 && c.report().consumed_frames == 3ull * block; }); const Report rc = c.report(); print_report("case c (starvation)", rc); + if (rc.accepted != 3) return fail("case c accepted block count", 9); if (rc.drained_ms < 250) return fail("case c drained interval too short", 9); if (rc.recovery_ms < 0) return fail("case c consumption did not recover", 10); if (rc.consumed_frames != 3ull * block) return fail("case c consumption incomplete", 10); @@ -148,7 +150,7 @@ int run() if (d.submit(ch6_44, 441, blk6.data()) != Submit::Accepted) return fail("case d 5.1 44.1 kHz block not accepted", 13); const Report rd = d.report(); - if (rd.unsupported != 1 || rd.submitted_frames + 2 < resampled_frame_count(441, 44100, mix.rate) || + if (rd.unsupported != 1 || rd.accepted != 1 || rd.submitted_frames + 2 < resampled_frame_count(441, 44100, mix.rate) || rd.submitted_frames > resampled_frame_count(441, 44100, mix.rate)) return fail("case d report counts mismatch", 14); } diff --git a/tests/startup_xapu_opus_count_check.cpp b/tests/startup_xapu_opus_count_check.cpp new file mode 100644 index 0000000000..c262995e60 --- /dev/null +++ b/tests/startup_xapu_opus_count_check.cpp @@ -0,0 +1,364 @@ +// Source-built checks for the optional XApu Opus telemetry: decoded packets, dequeued decoded +// completions, refusals by reason, and the stable summary line. Synthetic tones are encoded here +// with libopus; no game data or captured packet is used. +#include "startup_stubs/audio_telemetry.h" + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using ConnectFn = long(__cdecl*)(const void* input, void* output, void** handle); +using GetResultCountFn = std::uint32_t(__cdecl*)(void* handle, std::uint64_t unused); +using DequeueResultFn = long(__cdecl*)(void* handle, void* result); +using EnqueueCommandFn = long(__cdecl*)(void* handle, const void* command, std::uint64_t r8, std::uint64_t r9); +using DisconnectFn = long(__cdecl*)(void* handle); + +constexpr long hr_ok = 0; +constexpr long hr_pointer = static_cast(0x80004003); +constexpr long hr_handle = static_cast(0x80070006); +constexpr long hr_out_of_memory = static_cast(0x8007000E); +constexpr long hr_invalid_arg = static_cast(0x80070057); +constexpr long hr_fail = static_cast(0x80004005); +constexpr std::size_t result_size = 0x58; +constexpr std::size_t max_queue_entries = 16384; +constexpr unsigned char fill = 0xCD; + +int failures = 0; +ConnectFn connect; +GetResultCountFn get_count; +DequeueResultFn dequeue; +EnqueueCommandFn enqueue; +DisconnectFn disconnect; +void* handle; + +void check(bool condition, const char* label) +{ + if (condition) return; + ++failures; + std::printf("FAIL: %s\n", label); +} + +template +void put(std::array& cmd, std::size_t offset, T value) +{ + std::memcpy(cmd.data() + offset, &value, sizeof(value)); +} + +// Type 3 command with the fields one title fills. +std::array decode_cmd(std::uint32_t slot, float rate, std::uint32_t frames, const void* packet, + std::uint32_t packet_bytes, void* out, std::uint32_t out_bytes) +{ + std::array cmd{}; + put(cmd, 0x00, std::uint32_t{3}); + put(cmd, 0x04, slot); + put(cmd, 0x1C, rate); + put(cmd, 0x24, frames); + put(cmd, 0x28, packet_bytes); + put(cmd, 0x2C, reinterpret_cast(packet)); + put(cmd, 0x34, out_bytes); + put(cmd, 0x38, reinterpret_cast(out)); + return cmd; +} + +std::array plain_cmd(std::uint32_t type, std::uint32_t slot) +{ + std::array cmd{}; + put(cmd, 0x00, type); + put(cmd, 0x04, slot); + return cmd; +} + +std::vector tone_packet(int rate, int frames) +{ + int error = OPUS_OK; + OpusEncoder* encoder = opus_encoder_create(rate, 1, OPUS_APPLICATION_AUDIO, &error); + if (!encoder || error != OPUS_OK) return {}; + std::vector pcm(static_cast(frames)); + for (int i = 0; i < frames; ++i) + pcm[static_cast(i)] = + 0.5f * static_cast(std::sin(6.283185307179586 * 1000.0 * i / rate)); + std::vector packet(4000); + const int n = opus_encode_float(encoder, pcm.data(), frames, packet.data(), static_cast(packet.size())); + opus_encoder_destroy(encoder); + if (n <= 0) return {}; + packet.resize(static_cast(n)); + return packet; +} + +std::vector filled(std::size_t floats) +{ + std::vector buffer(floats); + std::memset(buffer.data(), fill, floats * sizeof(float)); + return buffer; +} + +bool untouched(const std::vector& buffer, std::size_t from = 0) +{ + const auto* bytes = reinterpret_cast(buffer.data()); + for (std::size_t i = from * sizeof(float); i < buffer.size() * sizeof(float); ++i) + if (bytes[i] != fill) return false; + return true; +} + +struct Result { + std::uint32_t type = 0xFFFFFFFFu, slot = 0xFFFFFFFFu, bytes = 0xFFFFFFFFu; +}; + +Result pop() +{ + std::array raw{}; + Result result; + if (dequeue(handle, raw.data()) != hr_ok) return result; + std::memcpy(&result.type, raw.data(), 4); + std::memcpy(&result.slot, raw.data() + 4, 4); + std::memcpy(&result.bytes, raw.data() + 0x34, 4); + return result; +} + +void expect_refused(const char* label, long want, const std::array& cmd, + const std::vector& out) +{ + check(enqueue(handle, cmd.data(), 0, 0) == want, label); + check(get_count(handle, 0) == 0, label); + check(untouched(out), label); +} + +std::string read_log(const char* path) +{ + HANDLE file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return {}; + std::string text; + char buffer[4096]; + for (;;) { + DWORD read = 0; + if (!ReadFile(file, buffer, sizeof(buffer), &read, nullptr) || read == 0) break; + text.append(buffer, read); + } + CloseHandle(file); + return text; +} + +struct Counts { + unsigned long long type3 = 0, packets = 0, completions = 0, refusals = 0; + unsigned long long invalid_argument = 0, opus_error = 0, capacity = 0, queue_full = 0; + unsigned long long short_command = 0, unknown_handle = 0, out_of_memory = 0, header = 0; +}; + +// Returns false on a malformed summary; counts every summary line in `lines`. +bool parse_summary(const std::string& text, Counts& counts, int& lines) +{ + counts = Counts{}; + lines = 0; + const char prefix[] = "x2w-audio XApu opus summary:"; + for (std::size_t start = 0; start < text.size();) { + const std::size_t end = text.find('\n', start); + const std::string line = text.substr(start, end == std::string::npos ? std::string::npos : end - start); + if (line.rfind(prefix, 0) == 0) { + Counts parsed; + const int fields = std::sscanf( + line.c_str(), + "x2w-audio XApu opus summary: type3=%llu packets=%llu completions=%llu refusals=%llu " + "invalid_argument=%llu opus_error=%llu capacity=%llu queue_full=%llu short_command=%llu " + "unknown_handle=%llu out_of_memory=%llu header=%llu", + &parsed.type3, &parsed.packets, &parsed.completions, &parsed.refusals, &parsed.invalid_argument, + &parsed.opus_error, &parsed.capacity, &parsed.queue_full, &parsed.short_command, + &parsed.unknown_handle, &parsed.out_of_memory, &parsed.header); + if (fields != 12) return false; + counts = parsed; + ++lines; + } + if (end == std::string::npos) break; + start = end + 1; + } + return true; +} + +void check_counts(const Counts& counts, const char* label) +{ + check(counts.type3 == 8, label); + check(counts.packets == 2, label); + check(counts.completions == 2, label); + check(counts.refusals == 7, label); + check(counts.invalid_argument == 1, label); + check(counts.opus_error == 1, label); + check(counts.capacity == 1, label); + check(counts.queue_full == 1, label); + check(counts.short_command == 1, label); + check(counts.unknown_handle == 1, label); + check(counts.out_of_memory == 0, label); + check(counts.header == 1, label); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) return std::printf("usage: startup_xapu_opus_count_check \n"), 2; + + // The saturation contract is independent of the endpoint: prove the helper stops at UINT64_MAX. + std::atomic bounded{(std::numeric_limits::max)() - 1}; + x2w_audio::saturating_add(bounded, 2); + check(bounded == (std::numeric_limits::max)(), "counter saturates at UINT64_MAX"); + x2w_audio::saturating_add(bounded); + check(bounded == (std::numeric_limits::max)(), "a saturated counter stays at UINT64_MAX"); + + char temp_path[MAX_PATH]{}; + char log_path[MAX_PATH]{}; + if (!GetTempPathA(MAX_PATH, temp_path) || !GetTempFileNameA(temp_path, "x2w-opus-", 0, log_path)) + return std::printf("FAIL: cannot create the telemetry log path\n"), 2; + SetEnvironmentVariableA("X2W_AUDIO_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_XAPU_TYPED_COMPLETIONS", "1"); + SetEnvironmentVariableA("X2W_TRAP_LOG", log_path); + + HMODULE module = LoadLibraryA(argv[1]); + if (!module) return std::printf("FAIL: cannot load %s\n", argv[1]), 2; + connect = reinterpret_cast(GetProcAddress(module, "XApuConnect")); + get_count = reinterpret_cast(GetProcAddress(module, "XApuGetResultCount")); + dequeue = reinterpret_cast(GetProcAddress(module, "XApuDequeueResult")); + enqueue = reinterpret_cast(GetProcAddress(module, "XApuEnqueueCommand")); + disconnect = reinterpret_cast(GetProcAddress(module, "XApuDisconnect")); + if (!connect || !get_count || !dequeue || !enqueue || !disconnect) + return std::printf("FAIL: missing export\n"), 2; + + std::array input{}; + const std::uint32_t buffer_bytes = 0x10000; + std::memcpy(input.data() + 0x0C, &buffer_bytes, sizeof(buffer_bytes)); + std::array output{}; + if (connect(input.data(), output.data(), &handle) != hr_ok || !handle) + return std::printf("FAIL: XApuConnect\n"), 2; + + const auto packet = tone_packet(48000, 960); + if (packet.empty()) return std::printf("FAIL: libopus produced no packet\n"), 2; + + // Two successful packets, each completion retired by the caller. + for (int i = 0; i < 2; ++i) { + auto out = filled(964); + const auto cmd = decode_cmd(0, 48000.0f, 960, packet.data(), static_cast(packet.size()), + out.data(), 3840); + check(enqueue(handle, cmd.data(), 0, 0) == hr_ok, "valid packet accepted"); + const Result result = pop(); + check(result.type == 3 && result.slot == 0 && result.bytes == 3840, "valid packet completes with 3840 bytes"); + check(untouched(out, 960), "valid packet leaves guard floats untouched"); + } + + // Malformed packet: libopus refuses it. + { + const unsigned char bad[] = {0x03, 0x00}; + auto out = filled(960); + expect_refused("malformed packet -> E_FAIL", hr_fail, + decode_cmd(1, 48000.0f, 960, bad, sizeof(bad), out.data(), 3840), out); + } + // Insufficient output capacity: libopus reports OPUS_BUFFER_TOO_SMALL for a 20 ms packet in 80 frames. + { + auto out = filled(964); + expect_refused("insufficient capacity -> E_FAIL", hr_fail, + decode_cmd(1, 48000.0f, 80, packet.data(), static_cast(packet.size()), + out.data(), 320), out); + } + // Invalid argument before libopus. + { + auto out = filled(960); + expect_refused("rate 44100 -> E_INVALIDARG", hr_invalid_arg, + decode_cmd(1, 44100.0f, 960, packet.data(), static_cast(packet.size()), + out.data(), 3840), out); + } + // A type 3 header whose decode fields cross a guard page. + if (auto* pages = static_cast(VirtualAlloc(nullptr, 0x2000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))) { + DWORD old = 0; + check(VirtualProtect(pages + 0x1000, 0x1000, PAGE_NOACCESS, &old) != FALSE, "guard page for short command"); + const auto full = decode_cmd(1, 48000.0f, 960, packet.data(), static_cast(packet.size()), + pages, 3840); + std::memcpy(pages + 0x1000 - 0x20, full.data(), 0x20); + check(enqueue(handle, pages + 0x1000 - 0x20, 0, 0) == hr_pointer, "short decode command -> E_POINTER"); + check(get_count(handle, 0) == 0, "short decode command queues nothing"); + VirtualFree(pages, 0, MEM_RELEASE); + } else { + check(false, "VirtualAlloc for short command"); + } + // A null header is a header refusal, not a type 3 one. + check(enqueue(handle, nullptr, 0, 0) == hr_pointer, "null command header -> E_POINTER"); + // A readable type 3 command on an unknown handle. + { + auto out = filled(960); + const auto cmd = decode_cmd(0, 48000.0f, 960, packet.data(), static_cast(packet.size()), + out.data(), 3840); + check(enqueue(reinterpret_cast(0xDEADBEEFULL), cmd.data(), 0, 0) == hr_handle, + "unknown handle -> E_HANDLE"); + } + // Queue cap: the decode is refused before it touches the slot's decoder. + { + bool filled_up = true; + for (std::uint32_t i = 0; i < max_queue_entries && filled_up; ++i) + filled_up = enqueue(handle, plain_cmd(4, 99).data(), 0, 0) == hr_ok; + check(filled_up && get_count(handle, 0) == max_queue_entries, "queue fills to 16384 entries"); + auto out = filled(960); + const auto cmd = decode_cmd(1, 48000.0f, 960, packet.data(), static_cast(packet.size()), + out.data(), 3840); + check(enqueue(handle, cmd.data(), 0, 0) == hr_out_of_memory, "full queue decode -> E_OUTOFMEMORY"); + check(untouched(out), "full queue refusal leaves output untouched"); + bool drained = true; + std::array raw{}; + for (std::size_t i = 0; i < max_queue_entries && drained; ++i) + drained = dequeue(handle, raw.data()) == hr_ok; + check(drained && get_count(handle, 0) == 0, "capped queue drains"); + } + + check(disconnect(handle) == hr_ok, "XApuDisconnect succeeds"); + + Counts counts; + int lines = 0; + const std::string log = read_log(log_path); + check(parse_summary(log, counts, lines), "summary line has the documented fields"); + check(lines == 1, "one summary line after the last disconnect"); + check_counts(counts, "summary counts successes and each refusal reason"); + + // Typed completions off: the same command is queued without decoding and the counters do not move. + SetEnvironmentVariableA("X2W_XAPU_TYPED_COMPLETIONS", nullptr); + void* second = nullptr; + check(connect(input.data(), output.data(), &second) == hr_ok && second != nullptr, "second XApuConnect"); + auto out = filled(960); + const auto untyped = decode_cmd(2, 48000.0f, 960, packet.data(), static_cast(packet.size()), + out.data(), 3840); + check(enqueue(second, untyped.data(), 0, 0) == hr_ok, "untyped type 3 accepted"); + std::array raw{}; + check(dequeue(second, raw.data()) == hr_ok, "untyped type 3 completion"); + check(untouched(out), "untyped type 3 leaves output untouched"); + check(disconnect(second) == hr_ok, "second XApuDisconnect succeeds"); + Counts unchanged; + int after = 0; + check(parse_summary(read_log(log_path), unchanged, after), "summary still parses"); + check(after == 1, "typed completions off do not add a summary line"); + check(unchanged.packets == 2 && unchanged.completions == 2, "typed completions off do not move the counters"); + + FreeLibrary(module); + int at_exit_lines = 0; + check(parse_summary(read_log(log_path), counts, at_exit_lines), "summary parses after unload"); + check(at_exit_lines == 1, "process exit does not repeat an unchanged summary"); + + DeleteFileA(log_path); + SetEnvironmentVariableA("X2W_TRAP_LOG", nullptr); + SetEnvironmentVariableA("X2W_XAPU_TYPED_COMPLETIONS", nullptr); + SetEnvironmentVariableA("X2W_AUDIO_PERMISSIVE", nullptr); + if (failures) return std::printf("%d failure(s)\n", failures), 1; + std::printf("PASS: startup_xapu_opus_count (%s)\n", opus_get_version_string()); + return 0; +} From aff14cbeddec20c3d0f770d854825fa5e7ae8aae Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 20:30:55 +0000 Subject: [PATCH 21/44] docs: point the scene-colour note at the switches section --- docs/experiments/startup-scene-color-report.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/experiments/startup-scene-color-report.md b/docs/experiments/startup-scene-color-report.md index 39921b9ecc..daedaa12a5 100644 --- a/docs/experiments/startup-scene-color-report.md +++ b/docs/experiments/startup-scene-color-report.md @@ -33,7 +33,7 @@ The runtime records one texel of render target 0 after each translated draw of decodes `rgba=` for `R8G8B8A8_UNORM`, `R8G8B8A8_UNORM_SRGB`, `B8G8R8A8_UNORM` and `B8G8R8A8_UNORM_SRGB`. The copy budget is 48, so a history that reaches 48 samples may be missing later draws. See [Per-draw texel history](../experiments.md#per-draw-texel-history) -and the [startup runtime options](../startup-runtime.md#environment-variables). +and the [startup runtime options](../startup-runtime.md#switches). The `draw=` value is the runtime copy ordinal, not a title draw-call number. It is monotonic in one process and is used here only to order the retained samples. @@ -110,3 +110,4 @@ The parser accepts only the version-1 header and the exact field order above. The BMP path accepts BI_RGB 24-bit or 32-bit images up to 16,384 pixels per side and 64 MiB. A 48-sample history is reported as truncated by design, even when the title happened to stop after exactly 48 copies. + From 35ee05e4350c8c86428f1ed8d78890c0c3f84aa6 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Fri, 27 Nov 2026 20:59:19 +0000 Subject: [PATCH 22/44] shader: emit 1e-6 as an exact bit pattern in rect geometry The DXIL assembler rejects the non-representable decimal literal; native_rectangle_pso_warp failed until the constant was built from 0x358637bd. --- src/gfx1013_rect_geometry.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/gfx1013_rect_geometry.cpp b/src/gfx1013_rect_geometry.cpp index b3107ee723..f0c1d64ed6 100644 --- a/src/gfx1013_rect_geometry.cpp +++ b/src/gfx1013_rect_geometry.cpp @@ -97,11 +97,14 @@ std::string native_rectangle_geometry(const std::vector &output auto &p = position[i], &a = position[(i + 1) % 3], &b = position[(i + 2) % 3]; auto across = distance2(a, b), to_a = distance2(p, a), to_b = distance2(p, b); // (p - a) . (p - b), squared, against 1e-6 of |p - a|^2 |p - b|^2: the two sides meet at a right angle. + // 1e-6 is not exactly representable; build it from its bit pattern because the DXIL assembler rejects + // the decimal literal. auto diff = [&](const string &u, const string &v) { return ir.value("fsub float " + u + ", " + v); }; auto times = [&](const string &u, const string &v) { return ir.value("fmul float " + u + ", " + v); }; auto dot = ir.value("fadd float " + times(diff(p[0], a[0]), diff(p[0], b[0])) + ", " + times(diff(p[1], a[1]), diff(p[1], b[1]))); - auto limit = ir.value("fmul float " + times(to_a, to_b) + ", 1.000000e-06"); + auto tolerance = ir.value("bitcast i32 897988541 to float"); // 0x358637bd = 1e-6f + auto limit = ir.value("fmul float " + times(to_a, to_b) + ", " + tolerance); geometric[i] = both(both(compare("ogt", across, to_a), compare("ogt", across, to_b)), compare("ole", times(dot, dot), limit)); } From a285b490575ea0ceb621704e85336dd587c8fe34 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 00:35:39 +0000 Subject: [PATCH 23/44] runtime: store compute token UAV descriptions in the merged view union --- src/startup_stubs/d3d12_compute_dispatch.inl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index da753bae17..b361d520a5 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -731,7 +731,7 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& views[i] = {token.resource, token.offset, token.bytes, true}; if (!reason && slot.half_typed_bytes) { views[i].described = true; - std::memcpy(views[i].desc, &token.view, sizeof(token.view)); + views[i].desc.uav = token.view; } continue; } From cf0b70727a9ae69736855f40bdba901cc1056e7c Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 01:32:20 +0000 Subject: [PATCH 24/44] shader: keep packed state and request shape validation after main merge --- src/gfx1013_compute_native.cpp | 4 ++++ src/shader_compute_request.cpp | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/src/gfx1013_compute_native.cpp b/src/gfx1013_compute_native.cpp index 15edb4dfa6..b8d1aeba9d 100644 --- a/src/gfx1013_compute_native.cpp +++ b/src/gfx1013_compute_native.cpp @@ -1745,6 +1745,10 @@ static NativeComputeShader translate_program(const ComputeRequest &request, unsi initial[next] = {Symbol::Type::table, compute_resource_heap}; initial[next + 1] = {Symbol::Type::table, compute_sampler_heap}; } + // Tagged slot-67 CS state packs group Z into the low 16 bits of word 4 + // and wave32 into bit 20. Leave untagged synthetic request ABIs alone. + const bool packed_state = !stage && direct_dxil && word(request.sa,0)==0x4005cf00 && + word(request.sa,4)==0x6c090102; // The legacy HLSL profile models wave32. Direct DXIL supports both guest wave sizes. A wave64 request whose // group has at most 32 threads stays on the wave32 model, as before the wave size was read: its one guest wave // has lanes 0..31 only, so EXEC's high word is zero and v_mbcnt_hi adds nothing for its lanes. The model diff --git a/src/shader_compute_request.cpp b/src/shader_compute_request.cpp index ff6d3a7e55..acbb8f56bd 100644 --- a/src/shader_compute_request.cpp +++ b/src/shader_compute_request.cpp @@ -254,6 +254,15 @@ x2w::ComputeRequest x2w::read_compute_request(const fs::path &marker) { wave32}; } +void x2w::validate_compute_request_shape(const ComputeRequest &r) { + check_compute_extents(r.description, r.code.size(), r.data.size(), r.sa.size(), r.sb.size()); + if (r.root.size() > (16u << 20) || r.code.size() > (1u << 20) || + r.data.size() > (1u << 20) || r.sa.size() > 4096 || r.sb.size() > 4096) + throw std::runtime_error("inconsistent compute request"); + if (r.root.empty() || r.sa.size() != 28 || r.code.empty() || r.data.empty() || r.code.size() % 4) + throw std::runtime_error(r.sa.size() != 28 ? "compute state block A is not 28 bytes" : "inconsistent compute request"); +} + std::string x2w::read_shader_container_bytes(const fs::path &file) { std::ifstream stream(file, std::ios::binary | std::ios::ate); auto length = stream.tellg(); From dc76ca16c1e8651ee5f4a5b6b1833b9c64b5db6d Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 02:26:43 +0000 Subject: [PATCH 25/44] runtime: read view-token compute inputs from non-aliased placed buffers --- src/startup_stubs/d3d12_draw.inl | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index ff46f62686..b9e94bbbe6 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2569,7 +2569,8 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor const Wrapper* owner = nullptr; bool own_memory = false; if (why) *why = nullptr; - if (words[0] == view_token_magic) { + const bool view_token_input = words[0] == view_token_magic; + if (view_token_input) { ViewRecord record{}; AcquireSRWLockShared(¬e_lock); if (words[1] < view_records().size()) record = view_records()[words[1]]; @@ -2642,7 +2643,9 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor owner = placed.owner; native = static_cast(owner->own().real); offset = address - reinterpret_cast(owner->own().title_memory); - if (!placed.alias && (!native || !list_copied_gpu_range(self, native, offset, bytes))) + // A view token already names a desktop resource and its range. Reading it does not require the + // title-memory alias used for raw guest addresses; the later resource/device/range checks still apply. + if (!view_token_input && !placed.alias && (!native || !list_copied_gpu_range(self, native, offset, bytes))) return refuse("an input is in a placed buffer that does not alias title memory"); } else if (own_memory) { native = static_cast(owner->own().real); From 2dff32de4a5da05125c727b7d1815d844e4cf899 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 04:24:15 +0000 Subject: [PATCH 26/44] runtime: pass input alignment after the title-snapshot flag --- src/startup_stubs/native_mesh57.inl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index b8455b82d3..f24e55f5cd 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -77,7 +77,7 @@ const char* bind_mesh57_buffers(Wrapper* self, Pass& pass, ID3D12GraphicsCommand view.Buffer.Flags != D3D12_BUFFER_SRV_FLAG_NONE || view.Buffer.StructureByteStride || !view.Buffer.NumElements || view.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING) return "selected MS heap SRV requires an R32_UINT buffer"; - typed = indirect_table_buffer(self, words, false, nullptr, u64{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP, 4); + typed = indirect_table_buffer(self, words, false, nullptr, u64{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP, false, 4); if (!typed.resource || typed.resource == arguments || typed.stride != 4 || typed.bytes != UINT64{view.Buffer.NumElements} * 4) return "selected MS heap SRV lacks its complete GPU-backed range"; From bb5ee4c9826173a259e335e22d9f579c30743a9b Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 04:24:15 +0000 Subject: [PATCH 27/44] runtime: prefer a published graphics pair over native compilation --- src/startup_stubs/d3d12_draw.inl | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 1995aeacbc..b14dd41222 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -671,9 +671,6 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void* (layout.empty() || publish_shader_request(key, L".ia", layout.data(), layout.size())) && (slot57_entry.empty() || publish_shader_request(key, L".ps57in", slot57_entry.data(), slot57_entry.size()))) publish_shader_request(key, L".a", a, a_bytes); -#ifdef X2W_NATIVE_SHADERS - if (try_native_graphics(*entry)) return entry; -#endif load_translation(*entry); } return entry; @@ -1277,11 +1274,15 @@ Translation* translation_for_targets(Translation* base, const Pass& pass) entry = new Translation; entry->key = key; entry->rtv_request = request; + load_translation(*entry, request); #ifdef X2W_NATIVE_SHADERS - if (GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr, 0) && - publish_shader_request(key, L".rtv", request.data(), request.size()) && try_native_graphics(*entry, true)) return entry; + if (entry->state != 1 && entry->manifest_retry.pending() && !entry->native_graphics_attempted && + GetEnvironmentVariableW(L"X2W_NATIVE_SHADERS", nullptr, 0) && + publish_shader_request(key, L".rtv", request.data(), request.size())) { + entry->native_graphics_attempted = true; + try_native_graphics(*entry, true); + } #endif - load_translation(*entry, request); if (entry->state != 1) { publish_shader_request(key, L".rtv", request.data(), request.size()); log("x2w-draw no RTV translation for %016llx (%s)", key, request.c_str()); From 3b5c7a88c440e9438b3fccc6cbc8998991525973 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 04:34:16 +0000 Subject: [PATCH 28/44] startup: confirm command list slots from the 261000 table The GXDK 261000 ID3D12GraphicsCommandList8 table confirms the command-list order: Reset and ClearState at 10-11, the query methods at 28-30, SetPredication at 31, the desktop marker methods at 56-58, ExecuteIndirect at 61 and the console reset at 139. It also confirms AllocateFromCommandAllocatorX at 148. Name the confirmed public methods and fix the query comments. The console-only rows stay outside the repository. Tests: startup_command_list_slot_names, startup_list_queries_warp and startup_list_queries_default_warp_control. --- docs/startup-runtime.md | 18 ++++---- src/startup_stubs/command_list_slot_names.h | 48 +++++++++++---------- src/startup_stubs/d3d12_xs_device.cpp | 14 +++--- tests/startup_command_list_slot_names.cpp | 30 +++++++------ 4 files changed, 59 insertions(+), 51 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 044f8decda..c14ef8e7a4 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -47,15 +47,13 @@ controls for other barrier types, flagged barriers, invalid resources and arrays ## Occlusion queries -Which console methods sit at command-list slots 28 to 30 is not established by any fixture here. The repository -places `ResourceBarrier` at 26 and four additional console methods in the 26 to 31 range -(32 is `SetDescriptorHeaps`, desktop 28 plus four). It also shows that -the plus-four run has ended by 61 (`ExecuteIndirect`, desktop 59 plus two). As a hypothesis, slots 28 to 30 are -implemented as `BeginQuery(heap, type, index)`, `EndQuery(heap, type, index)` and -`ResolveQueryData(heap, type, start, count, buffer, offset)`. Because that is a hypothesis, the bindings are a -diagnostic opt-in: only with `X2W_D3D12_QUERY_SLOTS=1` (in render mode) are the three slots bound. Unset, they stay -no-ops as before. The fixture below calls those slots directly, so it checks the forwarding, the refusals and the -end at Close, not the numbering. +The GXDK 261000 `ID3D12GraphicsCommandList8` table confirms `BeginQuery`, `EndQuery` and +`ResolveQueryData` at command-list slots 28 to 30, and `SetPredication` at 31. Slots 32 to 55 +are the desktop slots 28 to 51 plus four; slots 56 to 58 are `SetMarker`, `BeginEvent` and +`EndEvent`, and `ExecuteIndirect` is 61. The query bindings stay a diagnostic opt-in: only with +`X2W_D3D12_QUERY_SLOTS=1` (in render mode) are the three slots bound. Unset, they stay no-ops +as before. The fixture below calls those slots directly, so it checks the forwarding, the +refusals and the end at Close, not the numbering. The query heap comes from device slot 39 with the desktop desc, which the stand-in keeps. Only occlusion and binary-occlusion queries on an occlusion heap, recorded on a DIRECT list, are forwarded to the desktop list. A @@ -76,7 +74,7 @@ the console `Map`. It then checks that the refused calls, among them resolves ov with a hole and an index ended with the other occlusion type, leave the sentinel untouched with no debug-layer error, and it leaves one query open at Close. `startup_list_queries_default_{warp,hardware}_control` runs it without the switch: the slots stay no-ops and it must report the untouched sentinel in the first word. -`command_list_slot_names.h` still names 56 to 58 as the query methods by the plus-four rule. +Slots 56 to 58 are the desktop marker methods, not query methods. ## Depth target on translated draws diff --git a/src/startup_stubs/command_list_slot_names.h b/src/startup_stubs/command_list_slot_names.h index 472ef63155..4900e6d6de 100644 --- a/src/startup_stubs/command_list_slot_names.h +++ b/src/startup_stubs/command_list_slot_names.h @@ -2,25 +2,24 @@ // `x2w-noop` log so a line reads "CommandList::slot14(Dispatch)" instead of "CommandList::slot14". // Plain standard C++ with no Windows types, so the table can be compiled and tested on its own. // -// What is claimed, and why: -// - Slots 0 to 9 and 12 to 25 follow the public desktop ID3D12GraphicsCommandList order. The -// implemented slots agree with it at both ends of every run: 7 (GetDevice), 9 (Close), 12 and 13 -// (the draws), 20 to 23 (topology, viewports, scissors, blend factor) and 25 (pipeline state), so -// the slots between them (0 to 6, 8, 14 to 19, 24) take the desktop names. -// - Slots 10 and 11 are not named. The desktop order puts Reset and ClearState there, but this -// console list resets through slot 139, so the desktop order is not known to hold at 10 and 11. -// - Slot 26 accepts the UAV form of ResourceBarrier. Slots 27 to 31 are not named here. The slots -// that follow are the desktop ones moved up by four -// (32 is SetDescriptorHeaps, desktop 28), so four console methods sit somewhere in 26 to 31. -// As a hypothesis, d3d12_xs_device.cpp binds 28, 29 and 30 as BeginQuery, EndQuery and -// ResolveQueryData, only with the diagnostic X2W_D3D12_QUERY_SLOTS=1. No fixture here establishes -// which console methods sit there. -// - Slots 32 to 59 are named as the desktop slots 28 to 55 plus four. Implemented and checked -// against the desktop order: 32, 34, 36, 40, 42, 44, 47, 48, 50 and 52. Past 52 the rule is not -// checked: ExecuteIndirect (desktop 59) is at 61, desktop plus two, so the run of four has ended -// by then. The 56 to 58 names below are kept as the rule gives them. -// - Slots 61 (ExecuteIndirect) and 139 (Reset) are implemented in d3d12_xs_device.cpp. -// - Other slots have no confirmed meaning. +// The 0 to 61, 139 and 148 rows were checked against the GXDK 261000 +// ID3D12GraphicsCommandList8 function table through a local oracle outside the repository. The +// header itself is not copied into this repository; only the public desktop method names and the +// slot numbers are recorded. +// - Slots 0 to 8 are IUnknown, ID3D12Object and ID3D12DeviceChild. +// - 9 Close, 10 Reset and 11 ClearState. +// - 12 to 27 follow the desktop ID3D12GraphicsCommandList order through ExecuteBundle. +// - 28 to 31 are BeginQuery, EndQuery, ResolveQueryData and SetPredication. They sit before the +// desktop SetDescriptorHeaps rather than after DiscardResource. +// - 32 to 55 are the desktop slots 28 to 51 plus four: SetDescriptorHeaps through DiscardResource. +// - 56 to 58 are the unshifted desktop SetMarker, BeginEvent and EndEvent. +// - 59 and 60 are console-only marker methods and stay unnamed in this repository. +// - 61 is ExecuteIndirect (desktop 59, plus two). +// - 139 is the console reset path the title calls. The base Reset is at 10; the log calls the +// console path "Reset (console)" so both rows have distinct names. +// - 62 to 138 and 140 and above are console-only methods. They stay unnamed because their names +// and signatures are not needed by the current log. Slot 148 is the allocation path used by +// list_allocate_upload; it stays unnamed here for the same reason. #pragma once #include @@ -48,7 +47,9 @@ static_assert(desktop_method_count == 51, "ID3D12GraphicsCommandList has 51 meth inline constexpr int console_shift = 4; // console slot = desktop slot + 4, from SetDescriptorHeaps on inline constexpr int resource_barrier_slot = 26; inline constexpr int first_shifted_slot = 32; -inline constexpr int last_shifted_slot = 59; +inline constexpr int last_shifted_slot = 55; +inline constexpr int first_desktop_marker_slot = 56; +inline constexpr int last_desktop_marker_slot = 58; inline constexpr int execute_indirect_slot = 61; inline constexpr int reset_slot = 139; @@ -58,11 +59,14 @@ inline const char* name(int slot) noexcept const auto desktop = [](int index) { return desktop_names[index - first_desktop_method]; }; static constexpr const char* iunknown[] = {"QueryInterface", "AddRef", "Release", "GetPrivateData", "SetPrivateData", "SetPrivateDataInterface", "SetName", "GetDevice", "GetType"}; + static constexpr const char* query[] = {"BeginQuery", "EndQuery", "ResolveQueryData", "SetPredication"}; if (slot >= 0 && slot < first_desktop_method) return iunknown[slot]; - if (slot == first_desktop_method || (slot >= 12 && slot <= resource_barrier_slot)) return desktop(slot); + if (slot >= first_desktop_method && slot <= 27) return desktop(slot); + if (slot >= 28 && slot <= 31) return query[slot - 28]; if (slot >= first_shifted_slot && slot <= last_shifted_slot) return desktop(slot - console_shift); + if (slot >= first_desktop_marker_slot && slot <= last_desktop_marker_slot) return desktop(slot); if (slot == execute_indirect_slot) return "ExecuteIndirect"; - if (slot == reset_slot) return "Reset"; + if (slot == reset_slot) return "Reset (console)"; return nullptr; } diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 33c4f51f30..40cc3e5539 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3384,9 +3384,9 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_fixture_compute_root_uav(void* g return TRUE; } -// Query slots 28 to 30, as a hypothesis (command_list_slot_names.h): no fixture here establishes which console -// methods sit there, so they are bound only with X2W_D3D12_QUERY_SLOTS=1. The heap reaches device slot 39 with the -// desktop desc. Only occlusion queries are +// Query slots 28 to 30, confirmed by the GXDK 261000 ID3D12GraphicsCommandList6 function table +// (command_list_slot_names.h): they are bound only with X2W_D3D12_QUERY_SLOTS=1 because the behavior is +// diagnostic. The heap reaches device slot 39 with the desktop desc. Only occlusion queries are // forwarded (shortcut: other heap types are refused until a caller needs them); a call that does not fit the // heap it names is refused and logged with its values instead of reaching the desktop list. enum QueryMethod { begin_query, end_query, resolve_query }; @@ -6662,8 +6662,8 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_written_probe(void* address, uns // of its two display render targets the title pushes a bump allocator for allocatorId 0x80 that // serves pageSize 2 (bits 14-15) from a 64 MiB block, then asserts that the block was used up: // the console runtime evidently takes committed-resource memory from XMemAlloc with allocatorId -// 0x80. Hypothesis used here: attributes = pageSize (2 from 4 MiB up, else 1) << 14 | 0x80 << 16 | -// log2(alignment) << 24, memory type 0. The block is bookkeeping only; the desktop resource has its +// 0x80. Hypothesis used here: attributes = pageSize (2, a 2 MiB page, selected from 4 MiB up; else 1) +// << 14 | 0x80 << 16 | log2(alignment) << 24, memory type 0. The block is bookkeeping only; the desktop resource has its // own memory and does not alias it. using XMemAllocHook = void*(__stdcall*)(SIZE_T, ULONGLONG); XMemAllocHook title_alloc_hook() @@ -7676,8 +7676,8 @@ void build_tables() list_typed[47] = reinterpret_cast(&list_index_buffer); list_typed[48] = reinterpret_cast(&list_vertex_buffers); list_typed[x2w_list_slots::execute_indirect_slot] = reinterpret_cast(&list_execute_indirect); - // X2W_D3D12_QUERY_SLOTS=1 (diagnostic): which console methods sit at 28 to 30 is a hypothesis, so the query - // bindings are opt-in. Unset, the slots stay no-ops. + // X2W_D3D12_QUERY_SLOTS=1 (diagnostic): the 261000 table confirms BeginQuery, EndQuery and + // ResolveQueryData at 28 to 30, but the bindings stay opt-in. Unset, the slots stay no-ops. if (wchar_t on[4]{}; GetEnvironmentVariableW(L"X2W_D3D12_QUERY_SLOTS", on, 4) && on[0] == L'1') { list_typed[28] = reinterpret_cast(&list_begin_query); list_typed[29] = reinterpret_cast(&list_end_query); diff --git a/tests/startup_command_list_slot_names.cpp b/tests/startup_command_list_slot_names.cpp index a7e0602440..20d2e586cb 100644 --- a/tests/startup_command_list_slot_names.cpp +++ b/tests/startup_command_list_slot_names.cpp @@ -53,7 +53,7 @@ int main() {50, "OMSetRenderTargets"}, {52, "ClearRenderTargetView"}, {61, "ExecuteIndirect"}, - {139, "Reset"}, + {139, "Reset (console)"}, }; for (const auto& entry : handled) expect(is(entry.first, entry.second), "slot " + std::to_string(entry.first) + " is " + entry.second); @@ -61,12 +61,16 @@ int main() const std::vector> between = { {0, "QueryInterface"}, {1, "AddRef"}, {2, "Release"}, {3, "GetPrivateData"}, {4, "SetPrivateData"}, {5, "SetPrivateDataInterface"}, {6, "SetName"}, {8, "GetType"}, + {10, "Reset"}, {11, "ClearState"}, {14, "Dispatch"}, {15, "CopyBufferRegion"}, {16, "CopyTextureRegion"}, {17, "CopyResource"}, {18, "CopyTiles"}, {19, "ResolveSubresource"}, {24, "OMSetStencilRef"}, + {27, "ExecuteBundle"}, + {28, "BeginQuery"}, {29, "EndQuery"}, {30, "ResolveQueryData"}, {31, "SetPredication"}, + {56, "SetMarker"}, {57, "BeginEvent"}, {58, "EndEvent"}, }; for (const auto& entry : between) expect(is(entry.first, entry.second), "slot " + std::to_string(entry.first) + " is " + entry.second); - // From SetDescriptorHeaps on the console slot is the desktop slot plus four: 28 desktop methods in a row. + // From SetDescriptorHeaps through DiscardResource the console slot is the desktop slot plus four. const std::vector shifted = { "SetDescriptorHeaps", "SetComputeRootSignature", "SetGraphicsRootSignature", "SetComputeRootDescriptorTable", "SetGraphicsRootDescriptorTable", "SetComputeRoot32BitConstant", "SetGraphicsRoot32BitConstant", @@ -74,19 +78,21 @@ int main() "SetGraphicsRootConstantBufferView", "SetComputeRootShaderResourceView", "SetGraphicsRootShaderResourceView", "SetComputeRootUnorderedAccessView", "SetGraphicsRootUnorderedAccessView", "IASetIndexBuffer", "IASetVertexBuffers", "SOSetTargets", "OMSetRenderTargets", "ClearDepthStencilView", "ClearRenderTargetView", - "ClearUnorderedAccessViewUint", "ClearUnorderedAccessViewFloat", "DiscardResource", "BeginQuery", "EndQuery", - "ResolveQueryData", "SetPredication"}; - expect(shifted.size() == 28, "the shifted run has 28 methods"); + "ClearUnorderedAccessViewUint", "ClearUnorderedAccessViewFloat", "DiscardResource"}; + expect(shifted.size() == 24, "the shifted run has 24 methods"); for (std::size_t i = 0; i < shifted.size(); ++i) expect(is(32 + static_cast(i), shifted[i]), "slot " + std::to_string(32 + i) + " is " + shifted[i]); - // The run ends at 59 with the desktop slot 55; the desktop methods after it (56 to 59, plus four) are not named. - expect(is(59, "SetPredication"), "slot 59 is the desktop slot 55 plus four"); + // The run ends at 55 with DiscardResource; 56 to 58 keep the desktop marker names. + expect(is(55, "DiscardResource"), "slot 55 is the desktop slot 51 plus four"); + expect(is(56, "SetMarker"), "slot 56 is SetMarker"); + expect(is(57, "BeginEvent"), "slot 57 is BeginEvent"); + expect(is(58, "EndEvent"), "slot 58 is EndEvent"); // Slots that are not known stay unnamed: a name there would be a guess. - // 10 and 11: this console list resets through 139. 27 to 31: the remaining unconfirmed methods before the shift. - // Other slots from 60 up have unconfirmed meanings. -1 and 4096: outside the table. - std::vector unknown = {10, 11, 27, 28, 29, 30, 31, 60, 62, 63, 64, 66, 68, 70, 71, 72, 74, 75, 100, 126, - 131, 132, 138, 140, 142, 146, 255, 256, 999, 4096, -1, -100}; + // 59 and 60 are console-only markers; 62 and up are console-only methods not named in this table. + // 148 is the console allocation method and stays unnamed. -1 and 4096: outside the table. + std::vector unknown = {59, 60, 62, 63, 64, 66, 68, 70, 71, 72, 74, 75, 100, 126, + 131, 132, 138, 140, 142, 146, 147, 148, 149, 255, 256, 999, 4096, -1, -100}; for (const int slot : unknown) expect(x2w_list_slots::name(slot) == nullptr, "slot " + std::to_string(slot) + " has no name"); // Names are unique within the table and never empty, so a log line says which method it was. @@ -98,7 +104,7 @@ int main() for (const std::string& earlier : seen) expect(earlier != got, std::string("the name ") + got + " is used once"); seen.push_back(got); } - expect(seen.size() == 10 + 15 + 28 + 2, "the named slots are 0 to 9, 12 to 26, 32 to 59, 61 and 139"); + expect(seen.size() == 61, "the named slots are 0 to 58, 61 and 139"); if (failures) { std::fprintf(stderr, "%d check(s) failed\n", failures); From a26987920d1ea984f24977f3bb64cfa6cf3f2168 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 04:34:20 +0000 Subject: [PATCH 29/44] runtime: decode the 261000 xmem attribute layout The GDK 261000 XALLOC_ATTRIBUTES layout has objectType:14, pageSize:2, allocatorId:8, alignment:5, memoryType:4, an address-below-4-GiB bit at 33 and 30 reserved bits above it. Page size 2 is 2 MiB, not 4 MiB. Separate the address bit from the reserved field and refuse a below-4-GiB request explicitly until the allocator can honor it. Tests: era_heap_decode_fields, era_heap_failure and the other era_heap scenarios (10/10). --- src/era_heap.cpp | 10 ++++++-- src/era_heap.h | 13 ++++++----- tests/era_heap_check.cpp | 50 +++++++++++++++++++++++----------------- 3 files changed, 44 insertions(+), 29 deletions(-) diff --git a/src/era_heap.cpp b/src/era_heap.cpp index 25520fc730..10e0f15cfc 100644 --- a/src/era_heap.cpp +++ b/src/era_heap.cpp @@ -76,7 +76,8 @@ Fields decode(std::uint64_t attributes) noexcept static_cast((attributes >> 16) & 0xff), static_cast((attributes >> 24) & 0x1f), static_cast((attributes >> 29) & 0xf), - attributes >> 33, + static_cast((attributes >> 33) & 1), + static_cast((attributes >> 34) & 0x3fffffff), }; } @@ -87,6 +88,11 @@ void* allocate(std::size_t bytes, std::uint64_t attributes) noexcept if (bytes == 0 || fields.reserved != 0 || fields.page_size == 3) { return nullptr; } + // The title asked for an address below 4 GiB. This allocator does not yet provide + // one, so refuse instead of returning an address above that boundary. + if (fields.address_below_4gib) { + return nullptr; + } const auto alignment = std::size_t{1} << std::max(4u, fields.alignment); // Leave room for CRT alignment bookkeeping even for deliberately oversized input. const auto limit = static_cast(std::numeric_limits::max()); @@ -112,7 +118,7 @@ void* allocate(std::size_t bytes, std::uint64_t attributes) noexcept // SlimEra commits graphics memory as a separate virtual allocation. The desktop // places it on an allocation-granularity boundary (64 KiB on x64 Windows), which // covers 4 KB and 64 KB pages. Larger page sizes or alignments are not honored here. - constexpr std::size_t page_bytes[]{std::size_t{4} << 10, std::size_t{64} << 10, std::size_t{4} << 20}; + constexpr std::size_t page_bytes[]{std::size_t{4} << 10, std::size_t{64} << 10, std::size_t{2} << 20}; if (std::max(page_bytes[fields.page_size], alignment) > allocation_granularity()) { return nullptr; } diff --git a/src/era_heap.h b/src/era_heap.h index 3c288b390f..515468cfd0 100644 --- a/src/era_heap.h +++ b/src/era_heap.h @@ -3,20 +3,21 @@ #include #include -// Desktop handling of attribute words decoded with the public Xbox One ERA -// XALLOC_ATTRIBUTES layout (SlimEra era.h): objectType:14, pageSize:2, allocatorId:8, -// alignment:5, memoryType:4, reserved:31. That Scarlett uses this layout is an -// assumption; allocator-ID meaning and GPU visibility of graphics types are unconfirmed. +// Desktop handling of attribute words decoded with the XALLOC_ATTRIBUTES layout +// published by the GDK 261000 xmem.h: objectType:14, pageSize:2, allocatorId:8, +// alignment:5, memoryType:4, an address-below-4-GiB bit at 33 and reserved:30 above it. +// Allocator-ID meaning and GPU visibility of graphics types remain unconfirmed. // Heap and graphics memory types are served. Physical memory types, undefined // field values and alignments the desktop cannot honor return a null pointer. namespace era_heap { struct Fields { std::uint32_t object_type; - std::uint32_t page_size; // 0: 4 KB, 1: 64 KB, 2: 4 MB, 3: undefined + std::uint32_t page_size; // 0: 4 KB, 1: 64 KB, 2: 2 MB, 3: undefined std::uint32_t allocator_id; std::uint32_t alignment; // log2 of the requested alignment std::uint32_t memory_type; // 0: heap, 1-6: graphics, 7-9: physical - std::uint64_t reserved; + std::uint32_t address_below_4gib; // 1: the caller asks for an address below 4 GiB + std::uint32_t reserved; // 30 bits, must be zero }; Fields decode(std::uint64_t attributes) noexcept; diff --git a/tests/era_heap_check.cpp b/tests/era_heap_check.cpp index 79e66e7bc1..20a2e5c961 100644 --- a/tests/era_heap_check.cpp +++ b/tests/era_heap_check.cpp @@ -85,22 +85,27 @@ bool allocation_checks() bool failure_checks() { - // Mix each reserved bit with a valid heap alignment and with the AMD graphics word. - for (unsigned bit = 33; bit < 64; ++bit) { + // Mix each of the 30 reserved bits with a valid heap alignment and with the AMD graphics word. + for (unsigned bit = 34; bit < 64; ++bit) { const auto reserved = std::uint64_t{1} << bit; if (!rejects(257, reserved | (std::uint64_t{6} << 24)) || !rejects(512, reserved | amd_word)) { return false; } } + // The address-below-4-GiB bit is valid but this allocator does not provide such an address. + if (!rejects(257, (std::uint64_t{1} << 33) | (std::uint64_t{6} << 24)) || + !rejects(512, (std::uint64_t{1} << 33) | amd_word)) { + return false; + } // Physical memory types 7-9 are not modeled. Types 10-15 are undefined. for (std::uint64_t type = 7; type < 16; ++type) { if (!rejects(512, (amd_word & ~memory_type_mask) | (type << 29))) return false; } - // Graphics memory with 4 MB pages or a 128 KiB alignment exceeds the desktop + // Graphics memory with 2 MB pages or a 128 KiB alignment exceeds the desktop // allocation granularity. The undefined page size value 3 fails for every type. - const auto four_mb_pages = (amd_word & ~(std::uint64_t{3} << 14)) | (std::uint64_t{2} << 14); + const auto two_mb_pages = (amd_word & ~(std::uint64_t{3} << 14)) | (std::uint64_t{2} << 14); const auto wide_alignment = (amd_word & ~(std::uint64_t{31} << 24)) | (std::uint64_t{17} << 24); - if ((allocation_granularity() < (std::size_t{4} << 20) && !rejects(512, four_mb_pages)) || + if ((allocation_granularity() < (std::size_t{2} << 20) && !rejects(512, two_mb_pages)) || (allocation_granularity() < (std::size_t{1} << 17) && !rejects(512, wide_alignment)) || !rejects(512, amd_word | (std::uint64_t{3} << 14)) || !rejects(64, bink_word | (std::uint64_t{3} << 14))) { @@ -117,9 +122,9 @@ bool observed_word_checks() const auto bink = era_heap::decode(bink_word); const auto amd = era_heap::decode(amd_word); if (bink.object_type != 0 || bink.page_size != 0 || bink.allocator_id != 0xe5 || - bink.alignment != 5 || bink.memory_type != 0 || bink.reserved != 0 || + bink.alignment != 5 || bink.memory_type != 0 || bink.reserved != 0 || bink.address_below_4gib != 0 || amd.object_type != 0 || amd.page_size != 1 || amd.allocator_id != 0 || - amd.alignment != 8 || amd.memory_type != 5 || amd.reserved != 0) { + amd.alignment != 8 || amd.memory_type != 5 || amd.reserved != 0 || amd.address_below_4gib != 0) { return false; } @@ -404,8 +409,9 @@ bool concurrency_checks() return ok.load(); } -// Every field of the ERA attribute layout (objectType:14, pageSize:2, allocatorId:8, alignment:5, memoryType:4, -// reserved:31) at its widest value alone, all at once, and one word with a distinct value in each field. The +// Every field of the XALLOC_ATTRIBUTES layout (objectType:14, pageSize:2, allocatorId:8, alignment:5, memoryType:4, +// address-below-4-GiB:1, reserved:30) at its widest value alone, all at once, and one word with a distinct value +// in each field. The // observed words leave the object type and the reserved bits at 0, so a narrowed mask or a shifted field boundary // would decode them unchanged. narrow_object_type expects a 13-bit object type and is the negative control. bool decode_field_checks(bool narrow_object_type) @@ -416,16 +422,17 @@ bool decode_field_checks(bool narrow_object_type) era_heap::Fields fields; }; constexpr std::uint64_t mixed = 0x2a5cull | 2ull << 14 | 0xb7ull << 16 | 0x13ull << 24 | 9ull << 29 | - 0x5a5a5a5ull << 33; + 1ull << 33 | 0x2a5a5a5ull << 34; const Case cases[] = { - {"object type", 0x3fff, {0x3fff, 0, 0, 0, 0, 0}}, - {"page size", 3ull << 14, {0, 3, 0, 0, 0, 0}}, - {"allocator", 0xffull << 16, {0, 0, 0xff, 0, 0, 0}}, - {"alignment", 0x1full << 24, {0, 0, 0, 0x1f, 0, 0}}, - {"memory type", 0xfull << 29, {0, 0, 0, 0, 0xf, 0}}, - {"reserved", 0x7fffffffull << 33, {0, 0, 0, 0, 0, 0x7fffffff}}, - {"all ones", ~0ull, {0x3fff, 3, 0xff, 0x1f, 0xf, 0x7fffffff}}, - {"mixed", mixed, {0x2a5c, 2, 0xb7, 0x13, 9, 0x5a5a5a5}}, + {"object type", 0x3fff, {0x3fff, 0, 0, 0, 0, 0, 0}}, + {"page size", 3ull << 14, {0, 3, 0, 0, 0, 0, 0}}, + {"allocator", 0xffull << 16, {0, 0, 0xff, 0, 0, 0, 0}}, + {"alignment", 0x1full << 24, {0, 0, 0, 0x1f, 0, 0, 0}}, + {"memory type", 0xfull << 29, {0, 0, 0, 0, 0xf, 0, 0}}, + {"address 32-bit mapping", 1ull << 33, {0, 0, 0, 0, 0, 1, 0}}, + {"reserved", 0x3fffffffull << 34, {0, 0, 0, 0, 0, 0, 0x3fffffff}}, + {"all ones", ~0ull, {0x3fff, 3, 0xff, 0x1f, 0xf, 1, 0x3fffffff}}, + {"mixed", mixed, {0x2a5c, 2, 0xb7, 0x13, 9, 1, 0x2a5a5a5}}, }; bool ok = true; for (const auto& c : cases) { @@ -436,10 +443,11 @@ bool decode_field_checks(bool narrow_object_type) const auto got = era_heap::decode(c.word); if (got.object_type != want.object_type || got.page_size != want.page_size || got.allocator_id != want.allocator_id || got.alignment != want.alignment || - got.memory_type != want.memory_type || got.reserved != want.reserved) { - std::printf("FAIL: decode %s: %x %u %x %u %u %llx\n", c.name, got.object_type, got.page_size, + got.memory_type != want.memory_type || got.reserved != want.reserved || + got.address_below_4gib != want.address_below_4gib) { + std::printf("FAIL: decode %s: %x %u %x %u %u %x %u\n", c.name, got.object_type, got.page_size, got.allocator_id, got.alignment, got.memory_type, - static_cast(got.reserved)); + got.reserved, got.address_below_4gib); ok = false; } } From 250418b59d28071b34a597dbfad08d6eeb86c3aa Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 04:40:17 +0000 Subject: [PATCH 30/44] startup: name the confirmed command list table The query comment still cited ID3D12GraphicsCommandList6; the extracted 261000 table is GraphicsCommandList8. --- src/startup_stubs/d3d12_xs_device.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 40cc3e5539..8806c45f7b 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -3384,7 +3384,7 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_fixture_compute_root_uav(void* g return TRUE; } -// Query slots 28 to 30, confirmed by the GXDK 261000 ID3D12GraphicsCommandList6 function table +// Query slots 28 to 30, confirmed by the GXDK 261000 ID3D12GraphicsCommandList8 function table // (command_list_slot_names.h): they are bound only with X2W_D3D12_QUERY_SLOTS=1 because the behavior is // diagnostic. The heap reaches device slot 39 with the desktop desc. Only occlusion queries are // forwarded (shortcut: other heap types are refused until a caller needs them); a call that does not fit the From 676b2f9285fa41e26a500e60a20de08336b4aab7 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 04:50:28 +0000 Subject: [PATCH 31/44] docs: update the Era heap layout for the 261000 table Record the 2 MiB page-size value, the address-below-4-GiB bit at 33 and the 30 reserved bits at 34-63. Scope the older observed words to the zeros they measured and note that a below-4-GiB request still returns null. --- docs/experiments.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 5d92b84175..1a7b0abe64 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9280,14 +9280,14 @@ What is measured is the desktop behavior above. Under the ERA layout, the two re | CTest case | Inputs and checks | |---|---| | `era_heap_allocation` | Allocate 257 bytes using six alignment exponents. Check alignment of at least 16 bytes and the requested alignment, initial zeroing, writes and release. Debug builds also compare CRT heap snapshots. | -| `era_heap_failure` | Each reserved bit, combined with a heap alignment and with the AMD graphics word, returns a null pointer. So do memory types 7–15, page-size value 3, graphics memory with 4 MB pages or a 128 KiB alignment, zero size and excessive size. | +| `era_heap_failure` | Each of the 30 reserved bits (34–63) and the address-below-4-GiB bit at 33, combined with a heap alignment and with the AMD graphics word, return a null pointer. So do memory types 7–15, page-size value 3, graphics memory with 2 MB pages or a 128 KiB alignment, zero size and excessive size. | | `era_heap_reuse` | For three alignment exponents and three sizes, fill a block with `0xa5` and release it. Then hold up to 32 new blocks of the same shape until the released address returns. Every new block must read as zero. The output reports `recycled_address`, the number of the nine cases in which the CRT returned the dirty address. glibc returned all nine in a Linux build with a `posix_memalign` stand-in. Windows 11 build 26200.9974 with MSVC 14.44.35207 returned the dirty address in all nine cases in both Debug and Release. Low-fragmentation heap randomization can lower it. | -| `era_heap_observed_words` | Desktop handling of the two recorded words. Under the ERA layout, the Bink word `0x05e50000` splits into heap memory, 4 KB pages, allocator field `0xe5` and 32-byte alignment. The AMD word `0xa8004000` splits into memory type 5, 64 KB pages, allocator field 0 and 256-byte alignment. Bink-style 97- and 193-byte blocks are 32-byte aligned and zeroed, and each wrapper recovers its base. AMD-rounded requests of 256 to 65,792 bytes start a committed read-write region on a 64 KiB boundary and are zeroed and writable. After release, `VirtualQuery` reports the region as free. Nonzero object-type and allocator tags leave heap placement unchanged. | +| `era_heap_observed_words` | Desktop handling of the two recorded words. Under the ERA layout, the Bink word `0x05e50000` splits into heap memory, 4 KB pages, allocator field `0xe5` and 32-byte alignment. The AMD word `0xa8004000` splits into memory type 5, 64 KB pages, allocator field 0 and 256-byte alignment. The recorded words leave bit 33 and the 30 reserved bits at 0. Bink-style 97- and 193-byte blocks are 32-byte aligned and zeroed, and each wrapper recovers its base. AMD-rounded requests of 256 to 65,792 bytes start a committed read-write region on a 64 KiB boundary and are zeroed and writable. After release, `VirtualQuery` reports the region as free. Nonzero object-type and allocator tags leave heap placement unchanged. | | `era_heap_large_alignment` | Exponents 13, 16, 17, 20 and 31 with sizes of 1 and 257 bytes, one page, one page plus one byte and three pages minus one byte. Each block must be aligned and zeroed. `VirtualQuery` must report the block as the base of its own private read/write allocation, with a committed region equal to the payload rounded up to whole pages. After release the address must be `MEM_FREE`. The output reports the 25 cases, the committed bytes and the summed alignments. With the previous `_aligned_malloc` path, the first case already fails because the block lies inside a CRT heap allocation. | -| `era_heap_graphics_types` | Each graphics memory type 1–6 with 4 KB and 64 KB pages and alignment exponents 0, 4, 8 and 16, at 1 byte and one allocation granularity plus one byte. Exponent 16 is the 64 KiB granularity boundary itself. Each block must start on the granularity, be zeroed and writable, and be reported by `VirtualQuery` as the base of its own committed private read/write allocation. After release with the same attributes the address must be `MEM_FREE`. For every type, 4 MB pages, exponent 17 and page-size value 3 return a null pointer. The output reports 96 served and 18 rejected cases at granularity 65,536 on Windows 11 build 26200. Changing the granularity comparison from `>` to `>=` fails exponent 16 with 4 KB pages, and narrowing the graphics range to types 1–5 fails type 6; `era_heap_observed_words` catches only the first change. These are desktop policy checks; the console semantics of the six graphics types remain unconfirmed. | +| `era_heap_graphics_types` | Each graphics memory type 1–6 with 4 KB and 64 KB pages and alignment exponents 0, 4, 8 and 16, at 1 byte and one allocation granularity plus one byte. Exponent 16 is the 64 KiB granularity boundary itself. Each block must start on the granularity, be zeroed and writable, and be reported by `VirtualQuery` as the base of its own committed private read/write allocation. After release with the same attributes the address must be `MEM_FREE`. For every type, 2 MB pages, exponent 17 and page-size value 3 return a null pointer. The output reports 96 served and 18 rejected cases at granularity 65,536 on Windows 11 build 26200. Changing the granularity comparison from `>` to `>=` fails exponent 16 with 4 KB pages, and narrowing the graphics range to types 1–5 fails type 6; `era_heap_observed_words` catches only the first change. These are desktop policy checks; the console semantics of the six graphics types remain unconfirmed. | | `era_heap_concurrency` | Four threads run 100 rounds each. They hold simultaneous allocations, write distinct values, compare every byte and release the memory. | | `era_heap_caller_layout` | Owned desktop storage covers all 32 base residues at eight payload sizes. Each Bink-style wrapper recovers its original base after a payload write and preserves the surrounding guard bytes. Ten AMD-style requests check 256-byte size rounding and the unused tail. These cases establish caller-side arithmetic. The Bink-style storage uses the recorded Bink word. | -| `era_heap_decode_fields` | `decode` reads each field of the layout at its widest value with the other fields zero: object type `0x3fff`, page size 3, allocator `0xff`, alignment `0x1f`, memory type `0xf` and 31 reserved bits. It also reads an all-ones word and one word with a distinct value in every field. The recorded words leave the object type and the reserved bits at 0. So without this scenario, a 12-bit object-type mask and a reserved field taken from bit 32 both decoded them unchanged and passed every other scenario. `era_heap_decode_fields_control` expects a 13-bit object type and must fail. | +| `era_heap_decode_fields` | `decode` reads each field of the layout at its widest value with the other fields zero: object type `0x3fff`, page size 3, allocator `0xff`, alignment `0x1f`, memory type `0xf`, the address-below-4-GiB bit at 33 and the 30 reserved bits at 34–63. It also reads an all-ones word and one word with a distinct value in every field. The recorded words leave the object type, the address bit and the reserved bits at 0. So without this scenario, a 12-bit object-type mask and a reserved field starting at bit 34 both decoded them unchanged and passed every other scenario. `era_heap_decode_fields_control` expects a 13-bit object type and must fail. A word with bit 33 set is still refused by the allocator because it does not provide an address below 4 GiB. | `desktop_memory_query` supplies Windows observations for `XMemVirtualQuery` and `XMemGetWorkingSetStatistics`. The test reserves memory, commits and writes 1,024 pages, checks the read-only/writable boundary, then decommits. It verifies residency of a locked page and records working set, peak working set and private commit at three points. Values vary between runs. Scarlett structure layout, units and accounting scope remain unconfirmed. [Windows working sets](https://learn.microsoft.com/en-us/windows/win32/memory/working-set) From 7d3ae280e13383d09b4f72364c0a8d175b16d93e Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 04:55:05 +0000 Subject: [PATCH 32/44] docs: align the query slot table with the confirmed slots Keep the query bindings diagnostic while naming the confirmed methods. Leave the allocator page-size note to the xmem change. --- docs/startup-runtime.md | 2 +- src/startup_stubs/d3d12_xs_device.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index c14ef8e7a4..afd97770b5 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1643,7 +1643,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | | `X2W_D3D12_ROOT_SRV_AT_DRAW=1` | opt-in, render mode: a graphics root SRV (slot 44) without an upload mapping is not copied into the upload ring, since no draw reads that desktop binding (default: a 64 KiB copy at every slot 44 call). Translated draws copy the SRV themselves and are unaffected (`startup_root_srv_draw_*`). See [the experiment note](experiments/startup-root-srv-at-draw.md) | | `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1` | opt-in, render mode: a closed command list releases its upload ring chunks once its submit is fenced instead of holding them until Reset, and the ring grows in 16 MiB chunks up to 512 MiB (default: doubling chunks up to 256 MiB, holds until Reset). The larger ring can add up to about 1 GiB of process commit at peak (startup runs in the experiment note). A later submit of the same list before its Reset fences its unchanged chunks again; if one was reused in between, that list is refused before the execute and logged (`startup_address_console_gate_ring_keep_*`, `upload_reservation`). See [the experiment note](experiments/startup-upload-ring-release-at-submit.md) | -| `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops | +| `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the confirmed `BeginQuery`, `EndQuery` and `ResolveQueryData` methods (see [Occlusion queries](#occlusion-queries)). The bindings remain diagnostic because the forwarding behavior is not a console runtime oracle. Unset, the three slots stay no-ops | | `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat | | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | | `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | legacy diagnostic. Logs that clearing live slots is disabled and enables the existing retirement breakdown when base retirement and budgets are on ([details](#d3d12-resource-budget)) | diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 8806c45f7b..873e2dbab2 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -6662,8 +6662,8 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_written_probe(void* address, uns // of its two display render targets the title pushes a bump allocator for allocatorId 0x80 that // serves pageSize 2 (bits 14-15) from a 64 MiB block, then asserts that the block was used up: // the console runtime evidently takes committed-resource memory from XMemAlloc with allocatorId -// 0x80. Hypothesis used here: attributes = pageSize (2, a 2 MiB page, selected from 4 MiB up; else 1) -// << 14 | 0x80 << 16 | log2(alignment) << 24, memory type 0. The block is bookkeeping only; the desktop resource has its +// 0x80. Hypothesis used here: attributes = pageSize (2 from 4 MiB up, else 1) << 14 | 0x80 << 16 | +// log2(alignment) << 24, memory type 0. The block is bookkeeping only; the desktop resource has its // own memory and does not alias it. using XMemAllocHook = void*(__stdcall*)(SIZE_T, ULONGLONG); XMemAllocHook title_alloc_hook() From c8716216cf019da76f6bf73ceee5987babf1a428 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 04:55:12 +0000 Subject: [PATCH 33/44] runtime: note the two-MiB xmem page in the resource path Page size 2 is 2 MiB. This comment belongs with the XALLOC_ATTRIBUTES change rather than the command-list slot names. --- src/startup_stubs/d3d12_xs_device.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 33c4f51f30..16b4c4c07d 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -6662,8 +6662,8 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_written_probe(void* address, uns // of its two display render targets the title pushes a bump allocator for allocatorId 0x80 that // serves pageSize 2 (bits 14-15) from a 64 MiB block, then asserts that the block was used up: // the console runtime evidently takes committed-resource memory from XMemAlloc with allocatorId -// 0x80. Hypothesis used here: attributes = pageSize (2 from 4 MiB up, else 1) << 14 | 0x80 << 16 | -// log2(alignment) << 24, memory type 0. The block is bookkeeping only; the desktop resource has its +// 0x80. Hypothesis used here: attributes = pageSize (2, a 2 MiB page, selected from 4 MiB up; else 1) +// << 14 | 0x80 << 16 | log2(alignment) << 24, memory type 0. The block is bookkeeping only; the desktop resource has its // own memory and does not alias it. using XMemAllocHook = void*(__stdcall*)(SIZE_T, ULONGLONG); XMemAllocHook title_alloc_hook() From 6ed317e69aaadd9c00925bfe16608a95da46f327 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 05:02:29 +0000 Subject: [PATCH 34/44] docs: drop the allocator page-size note from the slot change --- src/startup_stubs/d3d12_xs_device.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 873e2dbab2..8806c45f7b 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -6662,8 +6662,8 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_written_probe(void* address, uns // of its two display render targets the title pushes a bump allocator for allocatorId 0x80 that // serves pageSize 2 (bits 14-15) from a 64 MiB block, then asserts that the block was used up: // the console runtime evidently takes committed-resource memory from XMemAlloc with allocatorId -// 0x80. Hypothesis used here: attributes = pageSize (2 from 4 MiB up, else 1) << 14 | 0x80 << 16 | -// log2(alignment) << 24, memory type 0. The block is bookkeeping only; the desktop resource has its +// 0x80. Hypothesis used here: attributes = pageSize (2, a 2 MiB page, selected from 4 MiB up; else 1) +// << 14 | 0x80 << 16 | log2(alignment) << 24, memory type 0. The block is bookkeeping only; the desktop resource has its // own memory and does not alias it. using XMemAllocHook = void*(__stdcall*)(SIZE_T, ULONGLONG); XMemAllocHook title_alloc_hook() From d77efc7d0b4a737c6a5e8101800da95635a0927e Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 05:06:34 +0000 Subject: [PATCH 35/44] docs: distinguish the 261000 layout from the SlimEra baseline Describe the current 261000 decoder, keep the older SlimEra observations scoped to their historical layout, include the below-4-GiB refusal, and replace the incorrect bit-34 mutation sentence. --- docs/experiments.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/experiments.md b/docs/experiments.md index 1a7b0abe64..2b5b0a7bcc 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9258,19 +9258,19 @@ On Windows build 26200, the pre-executable inventory covered 16 package DLLs and ## Heap and process memory -`src/era_heap.cpp` is a desktop handler. It splits the attribute word using SlimEra's Xbox One ERA layout: object type in bits 0–13, page size in bits 14–15, allocator ID in bits 16–23, log2 alignment in bits 24–28, memory type in bits 29–32 and reserved bits 33–63. Object type and allocator ID are carried as tags and do not affect placement, as in SlimEra's default heap. +`src/era_heap.cpp` now decodes the GDK 261000 XALLOC_ATTRIBUTES layout: object type in bits 0–13, page size in bits 14–15, allocator ID in bits 16–23, log2 alignment in bits 24–28, memory type in bits 29–32, an address-below-4-GiB bit at 33 and 30 reserved bits at 34–63. Object type and allocator ID are carried as tags and do not affect placement. The earlier desktop experiments compared the handler with SlimEra's Xbox One ERA layout, which treated bits 33–63 as reserved; those observations stay scoped to that historical layout. The desktop handling is: - **Heap (memory type 0):** served from the CRT heap at the requested alignment, minimum 16 bytes, and zero-filled. The page size does not affect these requests. SlimEra passes every heap request to `_aligned_malloc`, which commits the alignment padding as heap memory, so a 257-byte request with exponent 31 would commit more than 2 GiB. The desktop handler instead gives alignments above the page size their own reservation and commits only the pages that hold the payload; `VirtualAlloc` returns them zeroed. - **Graphics (memory types 1–6):** committed as a separate `VirtualAlloc` region. `release_with_attributes` frees it with `VirtualFree`. The region starts on the desktop allocation granularity, which covers 4 KB and 64 KB pages. This is ordinary CPU-visible memory; no GPU mapping or caching behavior is modeled. -- **Rejected:** physical memory types 7–9, undefined types 10–15, the undefined page-size value 3, reserved bits, and graphics requests whose page size or alignment exceeds the allocation granularity all return a null pointer. +- **Rejected:** physical memory types 7–9, undefined types 10–15, the undefined page-size value 3, the 30 reserved bits (34–63), the address-below-4-GiB bit (33), and graphics requests whose page size or alignment exceeds the allocation granularity all return a null pointer. A below-4-GiB request stays refused until the allocator can provide such an address. `release` frees heap allocations. It frees a page-backed block with `VirtualFree` when `VirtualQuery` reports it as the base of its own allocation; a CRT block never is, because `_aligned_malloc` stores its base pointer below the returned address. `release_with_attributes` takes the allocation's attribute word, as `XMemFree` callers do. -What is measured is the desktop behavior above. Under the ERA layout, the two recorded words give alignments that match their callers' own arithmetic: 32 bytes for Bink and 256 bytes for AMD. The following remain unconfirmed on Scarlett: +What is measured is the desktop behavior above. Under the 261000 layout, the two recorded words give alignments that match their callers' own arithmetic: 32 bytes for Bink and 256 bytes for AMD. The recorded words leave bit 33 and the 30 reserved bits at zero, so they do not by themselves distinguish the 261000 layout from the older SlimEra interpretation. The following remain unconfirmed on Scarlett: -- that Scarlett uses the ERA layout at all; +- whether the title's attribute words use the 261000 contract beyond the zero bits observed here; - what allocator ID `0xe5` means; - the GPU visibility and caching of memory type 5 and the other graphics types; - the console's error conventions. @@ -9282,12 +9282,12 @@ What is measured is the desktop behavior above. Under the ERA layout, the two re | `era_heap_allocation` | Allocate 257 bytes using six alignment exponents. Check alignment of at least 16 bytes and the requested alignment, initial zeroing, writes and release. Debug builds also compare CRT heap snapshots. | | `era_heap_failure` | Each of the 30 reserved bits (34–63) and the address-below-4-GiB bit at 33, combined with a heap alignment and with the AMD graphics word, return a null pointer. So do memory types 7–15, page-size value 3, graphics memory with 2 MB pages or a 128 KiB alignment, zero size and excessive size. | | `era_heap_reuse` | For three alignment exponents and three sizes, fill a block with `0xa5` and release it. Then hold up to 32 new blocks of the same shape until the released address returns. Every new block must read as zero. The output reports `recycled_address`, the number of the nine cases in which the CRT returned the dirty address. glibc returned all nine in a Linux build with a `posix_memalign` stand-in. Windows 11 build 26200.9974 with MSVC 14.44.35207 returned the dirty address in all nine cases in both Debug and Release. Low-fragmentation heap randomization can lower it. | -| `era_heap_observed_words` | Desktop handling of the two recorded words. Under the ERA layout, the Bink word `0x05e50000` splits into heap memory, 4 KB pages, allocator field `0xe5` and 32-byte alignment. The AMD word `0xa8004000` splits into memory type 5, 64 KB pages, allocator field 0 and 256-byte alignment. The recorded words leave bit 33 and the 30 reserved bits at 0. Bink-style 97- and 193-byte blocks are 32-byte aligned and zeroed, and each wrapper recovers its base. AMD-rounded requests of 256 to 65,792 bytes start a committed read-write region on a 64 KiB boundary and are zeroed and writable. After release, `VirtualQuery` reports the region as free. Nonzero object-type and allocator tags leave heap placement unchanged. | +| `era_heap_observed_words` | Desktop handling of the two recorded words. The words were measured under the older SlimEra interpretation and leave bit 33 and the 30 reserved bits at 0, so they do not distinguish the two layouts. The Bink word `0x05e50000` splits into heap memory, 4 KB pages, allocator field `0xe5` and 32-byte alignment. The AMD word `0xa8004000` splits into memory type 5, 64 KB pages, allocator field 0 and 256-byte alignment. Bink-style 97- and 193-byte blocks are 32-byte aligned and zeroed, and each wrapper recovers its base. AMD-rounded requests of 256 to 65,792 bytes start a committed read-write region on a 64 KiB boundary and are zeroed and writable. After release, `VirtualQuery` reports the region as free. Nonzero object-type and allocator tags leave heap placement unchanged. | | `era_heap_large_alignment` | Exponents 13, 16, 17, 20 and 31 with sizes of 1 and 257 bytes, one page, one page plus one byte and three pages minus one byte. Each block must be aligned and zeroed. `VirtualQuery` must report the block as the base of its own private read/write allocation, with a committed region equal to the payload rounded up to whole pages. After release the address must be `MEM_FREE`. The output reports the 25 cases, the committed bytes and the summed alignments. With the previous `_aligned_malloc` path, the first case already fails because the block lies inside a CRT heap allocation. | | `era_heap_graphics_types` | Each graphics memory type 1–6 with 4 KB and 64 KB pages and alignment exponents 0, 4, 8 and 16, at 1 byte and one allocation granularity plus one byte. Exponent 16 is the 64 KiB granularity boundary itself. Each block must start on the granularity, be zeroed and writable, and be reported by `VirtualQuery` as the base of its own committed private read/write allocation. After release with the same attributes the address must be `MEM_FREE`. For every type, 2 MB pages, exponent 17 and page-size value 3 return a null pointer. The output reports 96 served and 18 rejected cases at granularity 65,536 on Windows 11 build 26200. Changing the granularity comparison from `>` to `>=` fails exponent 16 with 4 KB pages, and narrowing the graphics range to types 1–5 fails type 6; `era_heap_observed_words` catches only the first change. These are desktop policy checks; the console semantics of the six graphics types remain unconfirmed. | | `era_heap_concurrency` | Four threads run 100 rounds each. They hold simultaneous allocations, write distinct values, compare every byte and release the memory. | | `era_heap_caller_layout` | Owned desktop storage covers all 32 base residues at eight payload sizes. Each Bink-style wrapper recovers its original base after a payload write and preserves the surrounding guard bytes. Ten AMD-style requests check 256-byte size rounding and the unused tail. These cases establish caller-side arithmetic. The Bink-style storage uses the recorded Bink word. | -| `era_heap_decode_fields` | `decode` reads each field of the layout at its widest value with the other fields zero: object type `0x3fff`, page size 3, allocator `0xff`, alignment `0x1f`, memory type `0xf`, the address-below-4-GiB bit at 33 and the 30 reserved bits at 34–63. It also reads an all-ones word and one word with a distinct value in every field. The recorded words leave the object type, the address bit and the reserved bits at 0. So without this scenario, a 12-bit object-type mask and a reserved field starting at bit 34 both decoded them unchanged and passed every other scenario. `era_heap_decode_fields_control` expects a 13-bit object type and must fail. A word with bit 33 set is still refused by the allocator because it does not provide an address below 4 GiB. | +| `era_heap_decode_fields` | `decode` reads each field of the layout at its widest value with the other fields zero: object type `0x3fff`, page size 3, allocator `0xff`, alignment `0x1f`, memory type `0xf`, the address-below-4-GiB bit at 33 and the 30 reserved bits at 34–63. It also reads an all-ones word and one word with a distinct value in every field. The recorded words leave the object type, the address bit and the reserved bits at 0. Without this scenario, a 12-bit object-type mask would decode the widest object type unchanged; the all-ones word and the address-bit case also distinguish the 30-bit reserved field from one that includes bit 33. `era_heap_decode_fields_control` expects a 13-bit object type and must fail. A word with bit 33 set is still refused by the allocator because it does not provide an address below 4 GiB. | `desktop_memory_query` supplies Windows observations for `XMemVirtualQuery` and `XMemGetWorkingSetStatistics`. The test reserves memory, commits and writes 1,024 pages, checks the read-only/writable boundary, then decommits. It verifies residency of a locked page and records working set, peak working set and private commit at three points. Values vary between runs. Scarlett structure layout, units and accounting scope remain unconfirmed. [Windows working sets](https://learn.microsoft.com/en-us/windows/win32/memory/working-set) From 15f8db3cb9394a748e2e21f3f179b954a20b9ed1 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 05:13:55 +0000 Subject: [PATCH 36/44] tooling: parse GDK MSVC class layouts --- docs/experiments/gdk-layouts.md | 40 ++++ tests/checks/python-linux/gdk_layouts.txt | 1 + tests/gdk_layouts_check.py | 173 ++++++++++++++ tools/gdk_abi_probe.py | 162 +++++++++++++ tools/gdk_layouts.py | 263 ++++++++++++++++++++++ 5 files changed, 639 insertions(+) create mode 100644 docs/experiments/gdk-layouts.md create mode 100644 tests/checks/python-linux/gdk_layouts.txt create mode 100644 tests/gdk_layouts_check.py create mode 100644 tools/gdk_abi_probe.py create mode 100644 tools/gdk_layouts.py diff --git a/docs/experiments/gdk-layouts.md b/docs/experiments/gdk-layouts.md new file mode 100644 index 0000000000..2aebd968d2 --- /dev/null +++ b/docs/experiments/gdk-layouts.md @@ -0,0 +1,40 @@ +# GDK layouts and ABI probes + +tools/gdk_layouts.py parses the output of MSVC /d1reportAllClassLayout and keeps +only class names, sizes, member names, offsets and flags. tools/gdk_abi_probe.py +turns that JSON into a C++ probe: static_asserts for a compile check, or a +program that prints sizeof and offsetof values for a GRDK/GXDK comparison. + +The logs are produced outside the repository. No GDK header, LIB or DLL enters +the tree. The parser is tested on a synthetic log with a base class, vftable, +bitfield, array and alignment member, so the Python check runs on Linux. + + python -B tests/gdk_layouts_check.py + python -B tools/gdk_layouts.py parse D:\gdk-oracle\fixtures\layout-xg-one.log --json out\xg.json --module xg_xs_gen8 --platform Gaming.Xbox.XboxOne.x64 --msvc 19.44.35207 + python -B tools/gdk_abi_probe.py generate --layouts out\xg.json --out out\xg-probe.cpp --include windows.h --include xg.h --prefix XG_ --print + +Measured on 28 November 2026 with MSVC 19.44.35207 and the 261000 headers: + +| Header | Platform | Classes in the log | Probe | +|---|---|---:|---| +| XboxOne/xg.h | Gaming.Xbox.XboxOne.x64 | 2,098 | 16 XG_ types; sizeof probe compiled | +| XboxOne/d3d12_x.h | Gaming.Xbox.XboxOne.x64 | 3,029 | 74 D3D12XBOX_ types; 25 anonymous skipped; compiled | +| GameInput.h | Gaming.Desktop.x64 | 3,344 | 41 GameInput types; 1 anonymous skipped; compiled | +| XGameRuntime.h | Gaming.Desktop.x64 | 3,363 | 30 selected public types; 3 anonymous skipped; compiled with windows.h first | + +The Xbox One headers use these macros: _GAMING_XBOX, _GAMING_XBOX_XBOXONE and +WINAPI_FAMILY=WINAPI_FAMILY_GAMES. The GRDK headers use _GAMING_DESKTOP and +WINAPI_FAMILY=WINAPI_FAMILY_DESKTOP_APP. XGameRuntime.h needs windows.h before +it, because XTaskQueue.h uses STDAPI. + +The parser treats a single-token member line, such as Width, as an unknown type +with a known name. MSVC prints that form for some typedefs. Anonymous nested +classes appear as NAME::; the probe generator skips them because +C++ cannot name them. + +Limits: a layout is a compile-time fact for one compiler and one macro set. It +does not prove runtime behavior, and a mismatch between a header layout and a +live library still needs an ABI probe or a runtime oracle. Private members and +non-standard-layout classes need review before offsetof is enabled; the generator +emits offsetof only for classes without bases or a vftable and for named, +non-bitfield fields. diff --git a/tests/checks/python-linux/gdk_layouts.txt b/tests/checks/python-linux/gdk_layouts.txt new file mode 100644 index 0000000000..059002a3c5 --- /dev/null +++ b/tests/checks/python-linux/gdk_layouts.txt @@ -0,0 +1 @@ +tests/gdk_layouts_check.py diff --git a/tests/gdk_layouts_check.py b/tests/gdk_layouts_check.py new file mode 100644 index 0000000000..ea57062b3f --- /dev/null +++ b/tests/gdk_layouts_check.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Checks for tools/gdk_layouts.py and tools/gdk_abi_probe.py. + +The synthetic log covers the MSVC constructs the knowledge parser needs: +nested classes, a base class, a vftable, bitfields, arrays and an alignment +member. No Windows or GDK is required. +""" + +import json +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import gdk_abi_probe as abi # noqa: E402 +import gdk_layouts as layouts # noqa: E402 + + +SYNTHETIC_LOG = """class Base\tsize(8): +\t+--- + 0\t| {vfptr} +\t+--- + +class Outer\tsize(24): +\t+--- + 0\t| +--- (base class Base) + 0\t| | {vfptr} +\t+--- + 8\t| UINT Width +12\t| UINT Flags : 3 +16\t| UCHAR Data[4] + \t| (size=4) +\t+--- + +class Outer::Inner\tsize(4): +\t+--- + 0\t| UINT Value +\t+--- + +class Single\tsize(4): +\t+--- + 0\t| Value +\t+--- +""" + + +def check(condition, what): + if not condition: + raise AssertionError(what) + + +def check_parser(): + with tempfile.TemporaryDirectory() as directory: + log = Path(directory) / "layout.log" + log.write_text(SYNTHETIC_LOG, encoding="utf-8") + classes = layouts.parse_log(log) + by_name = {item["name"]: item for item in classes} + check(set(by_name) == {"Base", "Outer", "Outer::Inner", "Single"}, f"classes {set(by_name)}") + outer = by_name["Outer"] + check(outer["size"] == 24, f"Outer size {outer['size']}") + check(outer["bases"] == [{"offset": 0, "name": "Base"}], f"bases {outer['bases']}") + check(outer["alignment"] == 4, f"alignment {outer['alignment']}") + members = {item["name"]: item for item in outer["members"] if item["name"]} + check(members["{vfptr}"]["kind"] == "vftable", "vftable kind") + check(members["Width"]["offset"] == 8, "Width offset") + check(members["Width"]["type"] == "UINT", "typed member") + check(members["Flags"]["bits"] == 3, "bitfield width") + check(members["Data"]["array"] == 4, "array count") + check(members[""]["kind"] == "alignment", "alignment member") + check(by_name["Outer::Inner"]["nested_in"] == "Outer", "nested_in") + check(by_name["Single"]["members"][0]["type"] == "unknown", "single-token member type") + check(by_name["Single"]["members"][0]["name"] == "Value", "single-token member name") + print("parser: base, vftable, bitfield, array and alignment passed") + + +def write_layouts(path, classes): + path.write_text( + json.dumps({"module": "synthetic", "classes": classes}, indent=2) + "\n", + encoding="utf-8", + ) + + +def check_compare(): + left = [ + {"name": "A", "size": 16, "bases": [], "members": [ + {"offset": 0, "type": "UINT", "name": "X", "bits": None, "kind": "field"}, + {"offset": 8, "type": "UINT", "name": "Y", "bits": None, "kind": "field"}, + ]}, + {"name": "OnlyLeft", "size": 4, "bases": [], "members": []}, + ] + right = [ + {"name": "A", "size": 24, "bases": [], "members": [ + {"offset": 0, "type": "UINT", "name": "X", "bits": None, "kind": "field"}, + {"offset": 12, "type": "UINT", "name": "Y", "bits": None, "kind": "field"}, + {"offset": 20, "type": "UINT", "name": "Z", "bits": None, "kind": "field"}, + ]}, + {"name": "OnlyRight", "size": 8, "bases": [], "members": []}, + ] + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + left_path = directory / "left.json" + right_path = directory / "right.json" + write_layouts(left_path, left) + write_layouts(right_path, right) + code = layouts.main(["compare", str(left_path), str(right_path), "--json", str(directory / "diff.json")]) + check(code == 1, f"compare exit {code}") + changes = json.loads((directory / "diff.json").read_text(encoding="utf-8")) + kinds = {(item["class"], item.get("kind")) for item in changes} + check(("A", "size") in kinds, f"size change {kinds}") + check(("A", "offset") in kinds, f"offset change {kinds}") + check(("OnlyLeft", "removed") in kinds and ("OnlyRight", "added") in kinds, f"add/remove {kinds}") + check(layouts.main(["compare", str(left_path), str(left_path)]) == 0, "identical exit") + print("compare: size, offset, add and remove changes passed") + + +def check_probe(): + classes = [ + {"name": "Simple", "size": 12, "bases": [], "members": [ + {"offset": 0, "type": "UINT", "name": "A", "bits": None, "kind": "field"}, + {"offset": 4, "type": "UINT", "name": "Flags", "bits": 3, "kind": "field"}, + {"offset": 8, "type": "UINT", "name": "B", "bits": None, "kind": "field"}, + ]}, + {"name": "Derived", "size": 16, "bases": [{"offset": 0, "name": "Simple"}], "members": [ + {"offset": 0, "type": "void*", "name": "{vfptr}", "bits": None, "kind": "vftable"}, + {"offset": 12, "type": "UINT", "name": "C", "bits": None, "kind": "field"}, + ]}, + ] + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + layout_path = directory / "layout.json" + write_layouts(layout_path, classes) + source = directory / "probe.cpp" + code = abi.main([ + "generate", "--layouts", str(layout_path), "--out", str(source), + "--include", "synthetic.h", "--offsetof", "--print", + ]) + check(code == 0, f"generate exit {code}") + text = source.read_text(encoding="utf-8") + check("#include " in text, "include") + check('static_assert(sizeof(Simple) == 12, "sizeof(Simple)");' in text, "sizeof Simple") + check('static_assert(offsetof(Simple, A) == 0, "offsetof(Simple, A)");' in text, "offsetof A") + check("offsetof(Simple, Flags)" not in text, "bitfield offset emitted") + check("offsetof(Derived, C)" not in text, "base-class offset emitted") + check('std::printf("offsetof(Simple, B)=%zu\\n", offsetof(Simple, B));' in text, "print B") + + log = directory / "probe.log" + log.write_text("sizeof(Simple)=12\noffsetof(Simple, A)=0\n", encoding="utf-8") + parsed = directory / "parsed.json" + check(abi.main(["parse", str(log), "--json", str(parsed)]) == 0, "parse exit") + facts = json.loads(parsed.read_text(encoding="utf-8"))["facts"] + check(facts == {"sizeof(Simple)": 12, "offsetof(Simple, A)": 0}, f"facts {facts}") + + changed = directory / "changed.json" + changed.write_text( + json.dumps({"facts": {"sizeof(Simple)": 16, "offsetof(Simple, A)": 0}}), + encoding="utf-8", + ) + check(abi.main(["diff", str(parsed), str(changed)]) == 1, "diff exit") + check(abi.main(["diff", str(parsed), str(parsed)]) == 0, "same diff exit") + print("probe: generation, offsetof rules, parse and diff passed") + + +def main(): + check_parser() + check_compare() + check_probe() + print("gdk_layouts_check: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_abi_probe.py b/tools/gdk_abi_probe.py new file mode 100644 index 0000000000..a16e8474af --- /dev/null +++ b/tools/gdk_abi_probe.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""Generate and compare C++ ABI probes from parsed GDK layouts. + +The layout JSON comes from tools/gdk_layouts.py. The generated probe can either +assert sizes and offsets at compile time or print them for a GRDK/GXDK diff. +Only names, sizes and offsets are used; private members and non-standard-layout +classes need an explicit review before offsetof is enabled. + +Commands: + generate --layouts --out [--include H]... [--print] [--offsetof] + parse [--json ] + diff +""" + +import argparse +import json +import re +import sys +from pathlib import Path + + +IDENTIFIER = re.compile(r"^[A-Za-z_]\w*$") +CLASS_NAME = re.compile(r"^(?:::)?[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*$") + + +def load_classes(path): + document = json.loads(Path(path).read_text(encoding="utf-8")) + return document, document.get("classes", []) + + +def member_offsets(block): + has_dynamic_layout = bool(block.get("bases")) or any( + item.get("kind") == "vftable" for item in block.get("members", []) + ) + if has_dynamic_layout: + return [] + offsets = [] + for item in block.get("members", []): + if item.get("kind") != "field" or item.get("bits") is not None: + continue + name = item.get("name", "") + if IDENTIFIER.fullmatch(name): + offsets.append((name, item["offset"])) + return offsets + + +def generate_command(args): + document, classes = load_classes(args.layouts) + if args.prefix: + classes = [ + block + for block in classes + if any(block["name"].startswith(prefix) for prefix in args.prefix) + ] + skipped = [block["name"] for block in classes if not CLASS_NAME.fullmatch(block["name"])] + classes = [block for block in classes if CLASS_NAME.fullmatch(block["name"])] + lines = [ + "// Generated by tools/gdk_abi_probe.py; do not edit.", + f"// module: {document.get('module', '')}", + f"// source: {document.get('header', '')}", + "", + ] + lines += [f"#include <{header}>" if not header.startswith('"') else f"#include {header}" for header in args.include] + lines.append("#include ") + if args.print: + lines.append("#include ") + lines.append("") + for block in classes: + name = block["name"] + lines.append(f'static_assert(sizeof({name}) == {block["size"]}, "sizeof({name})");') + if args.offsetof: + for member, offset in member_offsets(block): + lines.append( + f'static_assert(offsetof({name}, {member}) == {offset}, "offsetof({name}, {member})");' + ) + if args.print: + lines += ["", "int main()", "{"] + for block in classes: + name = block["name"] + lines.append(f' std::printf("sizeof({name})=%zu\\n", sizeof({name}));') + for member, _ in member_offsets(block): + lines.append( + f' std::printf("offsetof({name}, {member})=%zu\\n", offsetof({name}, {member}));' + ) + lines += [" return 0;", "}"] + Path(args.out).parent.mkdir(parents=True, exist_ok=True) + Path(args.out).write_text("\n".join(lines) + "\n", encoding="utf-8") + print( + json.dumps( + { + "classes": len(classes), + "skipped": len(skipped), + "offsetof": bool(args.offsetof), + "print": bool(args.print), + } + ) + ) + return 0 + + +def parse_command(args): + facts = {} + for line in Path(args.log).read_text(encoding="utf-8", errors="replace").splitlines(): + if "=" not in line: + continue + key, value = line.split("=", 1) + try: + facts[key.strip()] = int(value.strip(), 0) + except ValueError: + facts[key.strip()] = value.strip() + document = {"facts": facts} + if args.json: + Path(args.json).parent.mkdir(parents=True, exist_ok=True) + Path(args.json).write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"facts": len(facts)})) + return 0 + + +def diff_command(args): + left = json.loads(Path(args.left).read_text(encoding="utf-8")).get("facts", {}) + right = json.loads(Path(args.right).read_text(encoding="utf-8")).get("facts", {}) + changes = [] + for key in sorted(set(left) | set(right)): + if left.get(key) != right.get(key): + changes.append({"key": key, "left": left.get(key), "right": right.get(key)}) + if not changes: + print("no ABI differences") + return 0 + for change in changes: + print(json.dumps(change, sort_keys=True)) + return 1 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + + generate = sub.add_parser("generate", help="emit a C++ probe") + generate.add_argument("--layouts", required=True) + generate.add_argument("--out", required=True) + generate.add_argument("--include", action="append", default=[]) + generate.add_argument("--prefix", action="append", default=[]) + generate.add_argument("--offsetof", action="store_true") + generate.add_argument("--print", action="store_true") + generate.set_defaults(func=generate_command) + + parse = sub.add_parser("parse", help="parse a probe log") + parse.add_argument("log") + parse.add_argument("--json") + parse.set_defaults(func=parse_command) + + diff = sub.add_parser("diff", help="compare two parsed probe logs") + diff.add_argument("left") + diff.add_argument("right") + diff.set_defaults(func=diff_command) + + args = parser.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_layouts.py b/tools/gdk_layouts.py new file mode 100644 index 0000000000..1ab95b588e --- /dev/null +++ b/tools/gdk_layouts.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""Parse MSVC /d1reportAllClassLayout logs and compare two layout sets. + +The logs are produced outside the repository from GDK headers. This tool keeps +only sizes, offsets and member names, so the JSON can live in the local +knowledge base without copying header text. + +Commands: + parse ... --json [--module M] [--platform P] [--header H] + [--header-sha256 SHA] [--msvc VERSION] [--prefix P]... + compare [--json ] + +compare exits 1 when a class size or a named member offset differs. +""" + +import argparse +import hashlib +import json +import re +import sys +from pathlib import Path + + +HEADER_RE = re.compile(r"^(?:class|struct|union)\s+(.+?)\s+size\((\d+)\):") +MEMBER_RE = re.compile(r"^\s*(\d+)\s*\|\s*(.*?)\s*$") +ALIGNMENT_RE = re.compile(r"^\s*\|\s* \(size=(\d+)\)") +BASE_RE = re.compile(r"\+---\s*\(base class\s+(.+?)\)") +BITS_RE = re.compile(r":\s*(\d+)\s*$") +ARRAY_RE = re.compile(r"^(.*?)\s+([A-Za-z_]\w*)\s*\[(\d+)\]$") +NAMED_RE = re.compile(r"^(?P.+?)\s+(?P[A-Za-z_]\w*)$") +VFTABLE = "{vfptr}" + + +def sha256(path): + digest = hashlib.sha256() + digest.update(Path(path).read_bytes()) + return digest.hexdigest().upper() + + +def parse_member(offset, text): + if BASE_RE.search(text): + return { + "offset": offset, + "type": "", + "name": BASE_RE.search(text).group(1).strip(), + "bits": None, + "kind": "base", + } + if VFTABLE in text: + return {"offset": offset, "type": "void*", "name": VFTABLE, "bits": None, "kind": "vftable"} + + rest = text + bits = None + match = BITS_RE.search(rest) + if match: + bits = int(match.group(1)) + rest = rest[: match.start()].rstrip() + + array = None + match = ARRAY_RE.match(rest) + if match: + rest, count = match.group(1).strip(), int(match.group(3)) + array = count + name = match.group(2) + return { + "offset": offset, + "type": rest, + "name": name, + "bits": bits, + "kind": "field", + "array": array, + } + + match = NAMED_RE.match(rest) + if match: + return { + "offset": offset, + "type": match.group("type").strip(), + "name": match.group("name"), + "bits": bits, + "kind": "field", + } + if re.fullmatch(r"[A-Za-z_]\w*", rest): + return { + "offset": offset, + "type": "unknown", + "name": rest, + "bits": bits, + "kind": "field", + } + return { + "offset": offset, + "type": rest.strip(), + "name": "", + "bits": bits, + "kind": "unnamed", + } + + +def parse_log(path): + classes = [] + current = None + alignment = 0 + for line in Path(path).read_text(encoding="utf-8", errors="replace").splitlines(): + header = HEADER_RE.match(line) + if header: + if current is not None: + current["alignment"] = alignment + name = header.group(1).strip() + current = { + "name": name, + "size": int(header.group(2)), + "bases": [], + "members": [], + "alignment": 0, + "nested_in": name.rsplit("::", 1)[0] if "::" in name else None, + } + alignment = 0 + classes.append(current) + continue + if current is None: + continue + if line.strip().startswith("+---"): + continue + align = ALIGNMENT_RE.match(line) + if align: + alignment = int(align.group(1)) + current["members"].append( + { + "offset": current["size"] - alignment, + "type": "", + "name": "", + "bits": None, + "kind": "alignment", + } + ) + continue + member = MEMBER_RE.match(line) + if not member: + continue + text = re.sub(r"^(?:\|\s*)+", "", member.group(2)) + if not text.strip(): + continue + parsed = parse_member(int(member.group(1)), text) + if parsed["kind"] == "base": + current["bases"].append({"offset": parsed["offset"], "name": parsed["name"]}) + else: + current["members"].append(parsed) + if current is not None: + current["alignment"] = alignment + for block in classes: + seen = set() + unique = [] + for member in block["members"]: + key = (member["offset"], member["name"], member["kind"]) + if key not in seen: + seen.add(key) + unique.append(member) + block["members"] = unique + return classes + + +def parse_command(args): + classes = [] + sources = [] + for path in args.logs: + block = parse_log(path) + classes.extend(block) + sources.append({"log": str(path), "sha256": sha256(path), "classes": len(block)}) + if args.prefix: + classes = [item for item in classes if any(item["name"].startswith(prefix) for prefix in args.prefix)] + document = { + "sdk": args.sdk, + "module": args.module, + "platform": args.platform, + "header": args.header, + "header_sha256": args.header_sha256 or (sha256(args.header) if args.header else ""), + "msvc": args.msvc, + "source": "msvc-layout", + "logs": sources, + "classes": classes, + "stats": {"classes": len(classes), "bytes": sum(item["size"] for item in classes)}, + } + Path(args.json).parent.mkdir(parents=True, exist_ok=True) + Path(args.json).write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8") + print(json.dumps(document["stats"])) + return 0 + + +def index_classes(document): + return {item["name"]: item for item in document.get("classes", [])} + + +def compare_command(args): + left = json.loads(Path(args.left).read_text(encoding="utf-8")) + right = json.loads(Path(args.right).read_text(encoding="utf-8")) + left_classes = index_classes(left) + right_classes = index_classes(right) + changes = [] + for name in sorted(set(left_classes) | set(right_classes)): + old = left_classes.get(name) + new = right_classes.get(name) + if old is None: + changes.append({"class": name, "kind": "added", "right_size": new["size"]}) + continue + if new is None: + changes.append({"class": name, "kind": "removed", "left_size": old["size"]}) + continue + if old["size"] != new["size"]: + changes.append( + {"class": name, "kind": "size", "left_size": old["size"], "right_size": new["size"]} + ) + old_members = {item["name"]: item["offset"] for item in old["members"] if item.get("name") and item["kind"] == "field"} + new_members = {item["name"]: item["offset"] for item in new["members"] if item.get("name") and item["kind"] == "field"} + for member in sorted(set(old_members) | set(new_members)): + if old_members.get(member) != new_members.get(member): + changes.append( + { + "class": name, + "member": member, + "kind": "offset", + "left_offset": old_members.get(member), + "right_offset": new_members.get(member), + } + ) + if args.json: + Path(args.json).write_text(json.dumps(changes, indent=2) + "\n", encoding="utf-8") + if not changes: + print("no layout differences") + return 0 + for change in changes: + print(json.dumps(change, sort_keys=True)) + return 1 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + + parse = sub.add_parser("parse", help="parse MSVC layout logs") + parse.add_argument("logs", nargs="+") + parse.add_argument("--json", required=True) + parse.add_argument("--sdk", default="261000") + parse.add_argument("--module", default="") + parse.add_argument("--platform", default="") + parse.add_argument("--header", default="") + parse.add_argument("--header-sha256", default="") + parse.add_argument("--msvc", default="") + parse.add_argument("--prefix", action="append", default=[]) + parse.set_defaults(func=parse_command) + + compare = sub.add_parser("compare", help="compare two layout JSON files") + compare.add_argument("left") + compare.add_argument("right") + compare.add_argument("--json") + compare.set_defaults(func=compare_command) + + args = parser.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) From 79d3359e7df2da455919adf2fe415b35056962da Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 05:16:05 +0000 Subject: [PATCH 37/44] tooling: audit GDK export coverage --- docs/experiments/gdk-exports.md | 39 +++++ tests/checks/python-linux/gdk_exports.txt | 1 + tests/gdk_exports_check.py | 154 ++++++++++++++++ tools/gdk_exports.py | 167 ++++++++++++++++++ tools/gdk_shim_coverage.py | 203 ++++++++++++++++++++++ 5 files changed, 564 insertions(+) create mode 100644 docs/experiments/gdk-exports.md create mode 100644 tests/checks/python-linux/gdk_exports.txt create mode 100644 tests/gdk_exports_check.py create mode 100644 tools/gdk_exports.py create mode 100644 tools/gdk_shim_coverage.py diff --git a/docs/experiments/gdk-exports.md b/docs/experiments/gdk-exports.md new file mode 100644 index 0000000000..d16eb1c018 --- /dev/null +++ b/docs/experiments/gdk-exports.md @@ -0,0 +1,39 @@ +# GDK exports and shim coverage + +tools/gdk_exports.py reads captured dumpbin /exports text or a PE DLL and writes +an inventory with module, file, SHA-256, export name, ordinal and RVA. +tools/gdk_shim_coverage.py compares that inventory with the Xbox2Windows .def +files and writes a JSON matrix plus a Markdown table. + +The GDK libraries and the full inventory stay outside the repository. The +inventory used for the 261000 edition has 89 modules and 8,035 export names. +When a module has both a .lib and a .dll, the coverage tool merges their exports +and deduplicates the names, so d3d12_xs reports the union of the two files. + + python -B tests/gdk_exports_check.py + python -B tools/gdk_exports.py parse-dumpbin D:\gdk-oracle\dumpbin\xg_xs.txt --json out\xg_xs.json --kind dll + python -B tools/gdk_shim_coverage.py --exports D:\gdk-oracle\knowledge\exports-all.json --repo . --json out\coverage.json --markdown out\coverage.md + +Measured on 28 November 2026 with the 261000 LIB/DLL set: + +| Module | GDK functions | Shim functions | Covered | Missing | +|---|---:|---:|---:|---:| +| xmem | 36 | 27 | 13 | 23 | +| d3d12_xs | 28 | 5 | 4 | 24 | +| acphal | 10 | 10 | 9 | 1 | +| xapu | 6 | 6 | 5 | 1 | +| chad | 7 | 5 | 5 | 2 | +| xg_xs | 27 | 2 | 2 | 25 | +| xcrdapi | 1 | 3 | 1 | 0 | + +The xg_xs gap remains the largest: layout computation, DCC, tile shapes, +hardware-version setup and descriptor validation are not exported by the shim. +xmem lacks the statistics, tags, Win32 heap and configuration families. d3d12_xs +lacks the desktop D3D12 entry points and several DXGIX helpers; the IID list is +counted as data, not functions. + +The counts are names, not signatures and not tests. A name can exist with a +different calling convention, and a covered name can still be untested at +runtime. The ordinals are recorded where dumpbin prints them; a title that +imports by ordinal still needs the matching import library and a runtime check. +Xbox One gen8 libraries have their own names and are outside this table. diff --git a/tests/checks/python-linux/gdk_exports.txt b/tests/checks/python-linux/gdk_exports.txt new file mode 100644 index 0000000000..12598b2a55 --- /dev/null +++ b/tests/checks/python-linux/gdk_exports.txt @@ -0,0 +1 @@ +tests/gdk_exports_check.py diff --git a/tests/gdk_exports_check.py b/tests/gdk_exports_check.py new file mode 100644 index 0000000000..308f5cd4e8 --- /dev/null +++ b/tests/gdk_exports_check.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Checks for tools/gdk_exports.py and tools/gdk_shim_coverage.py. + +Uses synthetic dumpbin text and synthetic .def files. It needs neither Windows +nor the GDK; the PE scanner is a thin wrapper over pefile and is exercised by +the real inventory outside the repository. +""" + +import json +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import gdk_exports as exports # noqa: E402 +import gdk_shim_coverage as coverage # noqa: E402 + + +DLL_TEXT = """Microsoft (R) COFF/PE Dumper Version 14.44.35207.0 + +Dump of file xg_xs.dll + +File Type: DLL + + Exports + + ordinal hint RVA name + + 1 0 00001000 XGComputeBufferLayout + 2 1 00001200 XGComputeTexture2DLayout + 3 2 00001400 IID_IXGThing +""" + +LIB_TEXT = """Dump of file xmem.lib + +File Type: LIBRARY + +Exports + + ordinal name + + XMemAlloc + XMemFree + ?XMemInternal@@YAXXZ +""" + + +def check(condition, what): + if not condition: + raise AssertionError(what) + + +def check_parse(): + dll = exports.parse_dumpbin_text(DLL_TEXT) + check(dll == [ + {"ordinal": 1, "name": "XGComputeBufferLayout", "rva": "0x1000"}, + {"ordinal": 2, "name": "XGComputeTexture2DLayout", "rva": "0x1200"}, + {"ordinal": 3, "name": "IID_IXGThing", "rva": "0x1400"}, + ], f"DLL parse {dll}") + lib = exports.parse_dumpbin_text(LIB_TEXT) + check(lib == [ + {"ordinal": None, "name": "XMemAlloc", "rva": None}, + {"ordinal": None, "name": "XMemFree", "rva": None}, + {"ordinal": None, "name": "?XMemInternal@@YAXXZ", "rva": None}, + ], f"LIB parse {lib}") + + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + source = directory / "xg_xs.txt" + source.write_text(DLL_TEXT, encoding="utf-8") + output = directory / "exports.json" + code = exports.main([ + "parse-dumpbin", str(source), "--json", str(output), "--kind", "dll" + ]) + check(code == 0, f"parse-dumpbin exit {code}") + document = json.loads(output.read_text(encoding="utf-8")) + check(document["count"] == 3, f"count {document['count']}") + check(document["modules"][0]["module"] == "xg_xs", f"module {document['modules'][0]['module']}") + check(len(document["modules"][0]["sha256"]) == 64, "sha256") + print("exports: DLL, LIB, ordinal and CLI parsing passed") + + +def check_coverage(): + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + inventory = { + "sdk": "261000", + "modules": [ + { + "file": "xg_xs.dll", + "exports": [ + {"ordinal": 1, "name": "XGComputeBufferLayout", "rva": "0x1000"}, + {"ordinal": 2, "name": "XGComputeTexture2DLayout", "rva": "0x1200"}, + {"ordinal": 3, "name": "IID_IXGThing", "rva": "0x1400"}, + ], + }, + { + "file": "xmem.lib", + "exports": [ + {"ordinal": None, "name": "XMemAlloc", "rva": None}, + {"ordinal": None, "name": "XMemFree", "rva": None}, + ], + }, + ], + } + inventory_path = directory / "exports.json" + inventory_path.write_text(json.dumps(inventory), encoding="utf-8") + xg_def = directory / "xg_xs.def" + xg_def.write_text( + "LIBRARY xg_xs\nEXPORTS\nXGComputeBufferLayout\nIID_IXGThing DATA\nx2w_local\n", + encoding="utf-8", + ) + xmem_def = directory / "xmem.def" + xmem_def.write_text("LIBRARY xmem\nEXPORTS\nXMemAlloc\nXMemFree\n", encoding="utf-8") + output_json = directory / "coverage.json" + output_md = directory / "coverage.md" + code = coverage.main([ + "--exports", str(inventory_path), + "--def", "xg_xs=" + str(xg_def), + "--def", "xmem=" + str(xmem_def), + "--json", str(output_json), + "--markdown", str(output_md), + ]) + check(code == 0, f"coverage exit {code}") + rows = {row["module"]: row for row in json.loads(output_json.read_text(encoding="utf-8"))} + xg = rows["xg_xs"] + check(xg["gdk_functions"] == 2, f"xg functions {xg['gdk_functions']}") + check(xg["shim_functions"] == 2, f"xg shim functions {xg['shim_functions']}") + check(xg["covered_functions"] == 1, f"xg covered {xg['covered_functions']}") + check(xg["missing_functions"] == ["XGComputeTexture2DLayout"], f"xg missing {xg['missing_functions']}") + check(xg["covered_data"] == 1, f"xg data {xg['covered_data']}") + check(xg["extra"] == ["x2w_local"], f"xg extra {xg['extra']}") + check(xg["ordinals"] == { + "IID_IXGThing": 3, "XGComputeBufferLayout": 1, "XGComputeTexture2DLayout": 2 + }, f"xg ordinals {xg['ordinals']}") + check("| xg_xs | 2 | 2 | 1 | 1 |" in output_md.read_text(encoding="utf-8"), "markdown table") + check(coverage.main([ + "--exports", str(inventory_path), + "--def", "xg_xs=" + str(xg_def), + "--fail-on-missing", + ]) == 1, "fail-on-missing exit") + print("coverage: functions, data, extras, ordinals and exit codes passed") + + +def main(): + check_parse() + check_coverage() + print("gdk_exports_check: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_exports.py b/tools/gdk_exports.py new file mode 100644 index 0000000000..e71f162343 --- /dev/null +++ b/tools/gdk_exports.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Collect GDK export names and ordinals from dumpbin text or a PE DLL. + +The GDK libraries stay outside the repository. This tool writes the inventory +JSON that tools/gdk_shim_coverage.py compares with the shim .def files. + +Commands: + parse-dumpbin ... --json [--kind lib|dll] + scan-pe ... --json + +parse-dumpbin accepts a file or a directory of text captured from: + dumpbin /nologo /exports +""" + +import argparse +import hashlib +import json +import re +import sys +from pathlib import Path + + +DLL_ROW = re.compile(r"^\s*(\d+)\s+([0-9A-Fa-f]+)\s+([0-9A-Fa-f]+)\s+(\S+)\s*$") +LIB_ROW = re.compile(r"^\s*(\d+)?\s+([A-Za-z_?$@][^\s]*)\s*$") +SKIP = {"Exports", "Summary", "ordinal", "name", "hint", "RVA"} + + +def sha256(path): + digest = hashlib.sha256() + digest.update(Path(path).read_bytes()) + return digest.hexdigest().upper() + + +def parse_dumpbin_text(text): + exports = [] + started = False + for line in text.splitlines(): + if re.match(r"^\s*ordinal\s+name\b", line) or re.match( + r"^\s*ordinal\s+hint\s+RVA\s+name\b", line + ): + started = True + continue + if not started: + if line.strip() == "Exports": + started = True + continue + stripped = line.strip() + if not stripped: + continue + if stripped.startswith("Summary") or stripped.startswith("Dump of file"): + break + match = DLL_ROW.match(line) + if match: + exports.append( + { + "ordinal": int(match.group(1)), + "name": match.group(4), + "rva": "0x%X" % int(match.group(3), 16), + } + ) + continue + match = LIB_ROW.match(line) + if match and match.group(2) not in SKIP: + exports.append( + { + "ordinal": int(match.group(1)) if match.group(1) else None, + "name": match.group(2), + "rva": None, + } + ) + return exports + + +def module_name(path, kind): + return Path(path).stem + + +def collect_dumpbin(path, kind): + path = Path(path) + if path.is_dir(): + entries = sorted( + item for item in path.iterdir() if item.is_file() and item.suffix.lower() == ".txt" + ) + else: + entries = [path] + modules = [] + for entry in entries: + text = entry.read_text(encoding="utf-8", errors="replace") + modules.append( + { + "sdk": "261000", + "module": module_name(entry, kind), + "file": str(entry), + "kind": kind, + "sha256": sha256(entry), + "exports": parse_dumpbin_text(text), + } + ) + return modules + + +def scan_pe(path): + import pefile # Imported here so parse-dumpbin needs only the standard library. + + pe = pefile.PE(str(path), fast_load=True) + pe.parse_data_directories( + directories=[pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_EXPORT"]] + ) + exports = [] + directory = getattr(pe, "DIRECTORY_ENTRY_EXPORT", None) + if directory: + for symbol in directory.symbols: + exports.append( + { + "ordinal": symbol.ordinal, + "name": symbol.name.decode("ascii", "replace") if symbol.name else "", + "rva": "0x%X" % symbol.address, + } + ) + return { + "sdk": "261000", + "module": module_name(path, "dll"), + "file": str(path), + "kind": "dll", + "sha256": sha256(path), + "exports": exports, + } + + +def write_document(path, modules): + document = { + "sdk": "261000", + "count": sum(len(module["exports"]) for module in modules), + "modules": modules, + } + Path(path).parent.mkdir(parents=True, exist_ok=True) + Path(path).write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"modules": len(modules), "exports": document["count"]})) + return 0 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + + dumpbin = sub.add_parser("parse-dumpbin", help="parse captured dumpbin /exports text") + dumpbin.add_argument("inputs", nargs="+") + dumpbin.add_argument("--json", required=True) + dumpbin.add_argument("--kind", choices=("lib", "dll"), default="lib") + dumpbin.set_defaults( + func=lambda args: write_document( + args.json, + [module for path in args.inputs for module in collect_dumpbin(path, args.kind)], + ) + ) + + pe = sub.add_parser("scan-pe", help="read exports from a PE DLL") + pe.add_argument("dlls", nargs="+") + pe.add_argument("--json", required=True) + pe.set_defaults(func=lambda args: write_document(args.json, [scan_pe(path) for path in args.dlls])) + + args = parser.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_shim_coverage.py b/tools/gdk_shim_coverage.py new file mode 100644 index 0000000000..175be34863 --- /dev/null +++ b/tools/gdk_shim_coverage.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""Compare a GDK export inventory with the Xbox2Windows shim .def files. + +The inventory comes from tools/gdk_exports.py. An export name is not a +signature and not a test: this matrix prioritizes work, it does not claim full +coverage. + +Commands: + report --exports --repo [--json ] [--markdown ] + report --exports --def xmem=src/xmem_shim.def ... [--json ] +""" + +import argparse +import json +import sys +from pathlib import Path + + +DEFAULT_DEFS = { + "xmem": "src/xmem_shim.def", + "d3d12_xs": "src/d3d12_xs_shim.def", + "acphal": "src/startup_stubs/acphal.def", + "xapu": "src/startup_stubs/xapu.def", + "chad": "src/startup_stubs/chad.def", + "xg_xs": "src/startup_stubs/xg_xs.def", + "xcrdapi": "src/startup_stubs/xcrdapi.def", +} +DATA_PREFIXES = ("IID_", "WKPDID_") + + +def is_data(name): + return name.startswith(DATA_PREFIXES) + + +def read_def(path): + names = set() + ordinals = {} + data = set() + for line in Path(path).read_text(encoding="utf-8", errors="replace").splitlines(): + text = line.strip() + if not text or text.startswith(";") or text.upper().startswith("LIBRARY"): + continue + if text.upper() == "EXPORTS": + continue + name = text.split("=", 1)[0].split()[0] + ordinal = None + if "@" in name: + name, _, ordinal_text = name.partition("@") + try: + ordinal = int(ordinal_text) + except ValueError: + ordinal = None + if not name or name == "PRIVATE": + continue + if "DATA" in text.split(): + data.add(name) + names.add(name) + if ordinal is not None: + ordinals[name] = ordinal + return {"names": names, "ordinals": ordinals, "data": data} + + +def load_exports(document): + if isinstance(document, list): + modules = document + else: + modules = document.get("modules") or [document] + result = {} + for module in modules: + stem = Path(module["file"]).stem.lower() + entry = result.get(stem) + if entry is None: + entry = {"file": module["file"], "exports": []} + result[stem] = entry + entry["exports"].extend(module.get("exports", [])) + return result + + +def find_module(modules, name): + return modules.get(name.lower()) + + +def rows_for(args): + document = json.loads(Path(args.exports).read_text(encoding="utf-8")) + modules = load_exports(document) + definitions = {} + if args.repo: + for module, relative in DEFAULT_DEFS.items(): + path = Path(args.repo) / relative + if path.exists(): + definitions[module] = path + for item in args.defs: + module, separator, path = item.partition("=") + if not separator: + raise SystemExit("--def expects module=path: " + item) + definitions[module] = Path(path) + rows = [] + for module, def_path in sorted(definitions.items()): + shim = read_def(def_path) + gdk = find_module(modules, module) + if gdk is None: + continue + gdk_names = {item["name"] for item in gdk["exports"] if item.get("name")} + gdk_functions = {name for name in gdk_names if not is_data(name)} + gdk_data = {name for name in gdk_names if is_data(name)} + shim_functions = {name for name in shim["names"] if name not in shim["data"] and not is_data(name)} + shim_data = {name for name in shim["data"] if is_data(name)} + missing_functions = sorted(gdk_functions - shim_functions) + missing_data = sorted(gdk_data - shim_data) + ordinals = { + item["name"]: item["ordinal"] + for item in gdk["exports"] + if item.get("name") and item.get("ordinal") is not None + } + rows.append( + { + "module": module, + "gdk_lib": gdk["file"], + "def": str(def_path), + "gdk_exports": len(gdk_names), + "gdk_functions": len(gdk_functions), + "gdk_data": len(gdk_data), + "shim_exports": len(shim["names"]), + "shim_functions": len(shim_functions), + "shim_data": len(shim_data), + "covered_functions": len(gdk_functions & shim_functions), + "covered_data": len(gdk_data & shim_data), + "missing_functions": missing_functions, + "missing_data": missing_data, + "extra": sorted(shim["names"] - gdk_names), + "ordinals": {name: ordinals[name] for name in sorted(ordinals)}, + "def_ordinals": { + name: shim["ordinals"][name] for name in sorted(shim["ordinals"]) + }, + } + ) + return rows + + +def render_markdown(rows): + lines = [ + "# GDK export coverage of the Xbox2Windows shims", + "", + "| Module | GDK functions | Shim functions | Covered | Missing |", + "|---|---:|---:|---:|---:|", + ] + for row in rows: + lines.append( + "| {module} | {gdk_functions} | {shim_functions} | {covered_functions} | {missing} |".format( + missing=len(row["missing_functions"]), **row + ) + ) + lines += [ + "", + "Names only: an export is not a signature and not a test. Data exports", + "(IID_ and WKPDID_) are counted separately, and x2w_* locals are listed", + "as extras.", + "", + ] + for row in rows: + lines.append("## " + row["module"]) + lines.append("") + lines.append( + "Missing functions: " + + (", ".join(row["missing_functions"]) if row["missing_functions"] else "none") + ) + if row["missing_data"]: + lines.append("") + lines.append("Missing data: " + ", ".join(row["missing_data"])) + if row["extra"]: + lines.append("") + lines.append("Local extras: " + ", ".join(row["extra"])) + if row["ordinals"]: + lines.append("") + lines.append("GDK ordinals: " + ", ".join( + f"{name}@{ordinal}" for name, ordinal in row["ordinals"].items() + )) + lines.append("") + return "\n".join(lines) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--exports", required=True) + parser.add_argument("--repo") + parser.add_argument("--def", dest="defs", action="append", default=[]) + parser.add_argument("--json") + parser.add_argument("--markdown") + parser.add_argument("--fail-on-missing", action="store_true") + args = parser.parse_args(argv) + rows = rows_for(args) + if args.json: + Path(args.json).write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8") + markdown = render_markdown(rows) + if args.markdown: + Path(args.markdown).write_text(markdown + "\n", encoding="utf-8") + print(markdown) + missing = sum(len(row["missing_functions"]) for row in rows) + return 1 if args.fail_on_missing and missing else 0 + + +if __name__ == "__main__": + sys.exit(main()) From a7b111c3c14961294965faa9b0526b918a973cdb Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 05:18:57 +0000 Subject: [PATCH 38/44] tooling: extract GDK MSBuild platform profiles --- docs/experiments/gdk-platform-profiles.md | 40 +++ .../python-linux/gdk_platform_profiles.txt | 1 + tests/gdk_platform_profiles_check.py | 123 +++++++ tools/gdk_platform_profiles.py | 299 ++++++++++++++++++ 4 files changed, 463 insertions(+) create mode 100644 docs/experiments/gdk-platform-profiles.md create mode 100644 tests/checks/python-linux/gdk_platform_profiles.txt create mode 100644 tests/gdk_platform_profiles_check.py create mode 100644 tools/gdk_platform_profiles.py diff --git a/docs/experiments/gdk-platform-profiles.md b/docs/experiments/gdk-platform-profiles.md new file mode 100644 index 0000000000..ac480fab28 --- /dev/null +++ b/docs/experiments/gdk-platform-profiles.md @@ -0,0 +1,40 @@ +# GDK MSBuild platform profiles + +tools/gdk_platform_profiles.py reads the GDK platform files under +VS2022/flatDeployment/MSBuild/Microsoft/VC/v170 and writes a JSON profile per +platform. It keeps the MSBuild conditions and resolves the simple variables +defined in the same files. Variables that refer to the installed edition +(DurangoXdkInstallPath, DurangoGRDKInstallPath, XdkEdition) stay visible instead +of being guessed. + +The GDK installation and the JSON profiles stay outside the repository. + + python -B tests/gdk_platform_profiles_check.py + python -B tools/gdk_platform_profiles.py list --root D:\gdk-ref\261000\gxdk\Microsoft GDK\261000\GXDK + python -B tools/gdk_platform_profiles.py scan --root D:\gdk-ref\261000\gxdk\Microsoft GDK\261000\GXDK --platform Gaming.Xbox.Scarlett.x64 --json out\scarlett.json + +Measured on 28 November 2026 from the 261000 payload: + +| Platform | Sources | Defines | Includes | Libs | Dependencies | +|---|---:|---:|---:|---:|---:| +| Gaming.Desktop.x64 (GRDK) | 10 | 2 | 1 | 1 | 6 | +| Gaming.Xbox.Scarlett.x64 | 10 | 7 | 3 | 3 | 1 | +| Gaming.Xbox.XboxOne.x64 | 10 | 7 | 3 | 3 | 1 | + +The console profiles define _GAMING_XBOX, _GAMING_XBOX_SCARLETT or +_GAMING_XBOX_XBOXONE, WIN32_LEAN_AND_MEAN and +WINAPI_FAMILY=WINAPI_FAMILY_GAMES, plus the ATL/WRL strict-COM macros. The +desktop profile defines _GAMING_DESKTOP and +WINAPI_FAMILY=WINAPI_FAMILY_DESKTOP_APP. Gaming.Desktop.arm64 is not present in +this payload. + +The include and library roots are Console_EndpointIncludeRoot and +Console_EndpointLibRoot. The console dependency list in Console_Libs is +pixevt.lib, d3d12_xs.lib, gameinput.lib, xgameplatform.lib, xgameruntime.lib, +xmem.lib and xg_xs.lib. The Scarlett profile also sets +EnableEnhancedInstructionSet=AdvancedVectorExtensions, FloatingPointModel=Fast +and /favor:AMD64 for v142/v143. + +The profile is a build recipe, not a runtime fact. A fixture generated from it +still needs the matching compiler, Windows SDK and GDK edition; the unresolved +installation variables are kept exactly because their values differ per host. diff --git a/tests/checks/python-linux/gdk_platform_profiles.txt b/tests/checks/python-linux/gdk_platform_profiles.txt new file mode 100644 index 0000000000..f83b228b84 --- /dev/null +++ b/tests/checks/python-linux/gdk_platform_profiles.txt @@ -0,0 +1 @@ +tests/gdk_platform_profiles_check.py diff --git a/tests/gdk_platform_profiles_check.py b/tests/gdk_platform_profiles_check.py new file mode 100644 index 0000000000..5411d37370 --- /dev/null +++ b/tests/gdk_platform_profiles_check.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Checks for tools/gdk_platform_profiles.py. + +Builds a small MSBuild platform tree in a temporary directory. No GDK or +Windows is required. +""" + +import json +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import gdk_platform_profiles as profiles # noqa: E402 + + +NAMESPACE = 'xmlns="http://schemas.microsoft.com/developer/msbuild/2003"' + + +def write(path, body): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + f"\n{body}\n\n", encoding="utf-8" + ) + + +def make_tree(root): + platform = ( + root + / "VS2022" + / "flatDeployment" + / "MSBuild" + / "Microsoft" + / "VC" + / "v170" + / "Platforms" + / "Gaming.Xbox.Scarlett.x64" + ) + write( + platform / "261000" / "Platform.Common.props", + """ + true + Unicode + + + + _GAMING_XBOX;_GAMING_XBOX_SCARLETT;%(PreprocessorDefinitions) + $(XdkEditionRootVS2022)Include;%(AdditionalIncludeDirectories) + /favor:AMD64 %(AdditionalOptions) + Fast + + + xgameplatform.lib + MachineX64 + + """, + ) + write( + platform / "Platform.props", + """ + D:\\gdk\\ + """, + ) + write(platform / "Platform.targets", " 261000") + write( + platform / "PlatformToolsets" / "v143" / "Toolset.props", + """ + + MultiThreadedDLL + + """, + ) + return platform + + +def check(condition, what): + if not condition: + raise AssertionError(what) + + +def main(): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + make_tree(root) + + found = profiles.choose(root, "Gaming.Xbox.Scarlett.x64", "v170", "261000") + check(found is not None, "platform not found") + check(found.name == "Gaming.Xbox.Scarlett.x64", f"platform {found.name}") + + listed = profiles.main(["list", "--root", str(root)]) + check(listed == 0, f"list exit {listed}") + + output = root / "profile.json" + code = profiles.main([ + "scan", "--root", str(root), "--platform", "Gaming.Xbox.Scarlett.x64", + "--json", str(output), + ]) + check(code == 0, f"scan exit {code}") + document = json.loads(output.read_text(encoding="utf-8")) + check(document["platform"] == "Gaming.Xbox.Scarlett.x64", "platform name") + check(document["defines"] == ["_GAMING_XBOX", "_GAMING_XBOX_SCARLETT"], f"defines {document['defines']}") + check(document["includes"] == ["D:\\gdk\\Include"], f"includes {document['includes']}") + check(document["dependencies"] == ["xgameplatform.lib"], f"deps {document['dependencies']}") + check(document["flags"]["floating_point_model"] == "Fast", "floating point") + check(document["flags"]["runtime_library"] == "MultiThreadedDLL", "runtime library") + check(document["flags"]["target_machine"] == "MachineX64", "target machine") + check(document["flags"]["character_set"] == "Unicode", "character set") + conditions = document["properties"]["UseDebugLibraries"] + check(conditions[0]["condition"] == "'$(Configuration)'=='Debug'", f"condition {conditions}") + check(len(document["sources"]) == 4, f"sources {len(document['sources'])}") + + missing = profiles.main([ + "scan", "--root", str(root), "--platform", "Gaming.Desktop.x64", + "--json", str(root / "missing.json"), + ]) + check(missing == 2, f"missing platform exit {missing}") + print("gdk_platform_profiles_check: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/gdk_platform_profiles.py b/tools/gdk_platform_profiles.py new file mode 100644 index 0000000000..8091133008 --- /dev/null +++ b/tools/gdk_platform_profiles.py @@ -0,0 +1,299 @@ +#!/usr/bin/env python3 +"""Extract GDK MSBuild platform properties into JSON. + +The GDK installation stays outside the repository. This reads the canonical +VS2022/flatDeployment platform files, keeps the MSBuild conditions and resolves +the simple variables defined in the same files. Unresolved variables remain +visible instead of being guessed. + +Commands: + list --root [--vs v170] [--sdk 261000] + scan --root --platform --json [--vs v170] [--sdk 261000] +""" + +import argparse +import hashlib +import json +import re +import sys +import xml.etree.ElementTree as ET +from pathlib import Path + + +NS = "{http://schemas.microsoft.com/developer/msbuild/2003}" +VARIABLE = re.compile(r"\$\(([A-Za-z_][A-Za-z0-9_]*)\)") +PROPERTY_NAMES = ("PropertyGroup", "ItemDefinitionGroup", "ItemGroup") + + +def tag(element): + return element.tag.rsplit("}", 1)[-1] + + +def sha256(path): + digest = hashlib.sha256() + digest.update(Path(path).read_bytes()) + return digest.hexdigest().upper() + + +def platform_dirs(root): + root = Path(root) + found = {} + for candidate in root.rglob("Platform.props"): + directory = candidate.parent + found[str(directory).lower()] = directory + return list(found.values()) + + +def score(directory, vs, sdk): + parts = [part.lower() for part in directory.parts] + value = 0 + if "vs2022" in parts: + value += 20 + if vs.lower() in parts: + value += 10 + if "flatdeployment" in parts: + value += 5 + if sdk in parts: + value += 3 + return value + + +def choose(root, platform, vs, sdk): + matches = [item for item in platform_dirs(root) if item.name.lower() == platform.lower()] + if not matches: + return None + return max(matches, key=lambda item: (score(item, vs, sdk), -len(str(item)))) + + +def list_command(args): + rows = [] + by_name = {} + for directory in platform_dirs(args.root): + candidate = { + "platform": directory.name, + "path": str(directory), + "score": score(directory, args.vs, args.sdk), + } + key = directory.name.lower() + if key not in by_name or candidate["score"] > by_name[key]["score"]: + by_name[key] = candidate + rows = list(by_name.values()) + rows.sort(key=lambda item: item["platform"].lower()) + for row in rows: + print(f"{row['platform']}\t{row['path']}") + return 0 + + +def parse_file(path, properties, items, sources): + sources.append({"path": str(path), "sha256": sha256(path)}) + tree = ET.parse(path) + root = tree.getroot() + for group in root: + name = tag(group) + condition = group.get("Condition", "") + if name == "PropertyGroup": + for child in group: + key = tag(child) + value = (child.text or "").strip() + properties.setdefault(key, []).append( + { + "value": value, + "condition": child.get("Condition", condition), + "file": Path(path).name, + } + ) + elif name == "ItemDefinitionGroup": + for item in group: + item_name = tag(item) + bucket = items.setdefault(item_name, {}) + for child in item: + key = tag(child) + bucket.setdefault(key, []).append( + { + "value": (child.text or "").strip(), + "condition": child.get("Condition", condition), + } + ) + + +def table(properties): + result = {} + for key, entries in properties.items(): + value = entries[-1]["value"] + if f"$({key})" in value: + continue + result[key] = value + return result + + +def resolve(text, variables, depth=0, seen=None): + if depth > 8 or not text: + return text + seen = set() if seen is None else seen + + def replace(match): + name = match.group(1) + if name in seen: + return match.group(0) + value = variables.get(name) + if value is None: + return match.group(0) + return resolve(value, variables, depth + 1, seen | {name}) + + replaced = VARIABLE.sub(replace, text) + if len(replaced) > 16384: + return replaced[:16384] + if replaced == text: + return text + return resolve(replaced, variables, depth + 1, seen) + + +def split_list(text): + if not text: + return [] + values = [] + for item in text.split(";"): + item = item.strip() + if not item or item.startswith("%("): + continue + values.append(item) + return values + + +def last_item(items, group, key): + entries = items.get(group, {}).get(key, []) + return entries[-1]["value"] if entries else "" + + +def combined(items, group, key, separator): + entries = items.get(group, {}).get(key, []) + return separator.join(entry["value"] for entry in entries if entry["value"]) + + +def scan_command(args): + directory = choose(args.root, args.platform, args.vs, args.sdk) + if directory is None: + print(f"platform not found: {args.platform}", file=sys.stderr) + return 2 + sources = [] + properties = {} + items = {} + files = [ + directory / "Platform.default.props", + directory / "261000" / "Platform.Common.props", + directory / "261000" / "Platform.Edition.default.props", + directory / "261000" / "Platform.Edition.props", + directory / "261000" / "Platform.Edition.targets", + directory / "261000" / "Platform.Commandline.targets", + directory / "Platform.props", + directory / "Platform.targets", + ] + toolset_root = directory / "PlatformToolsets" + if toolset_root.exists(): + files += sorted(toolset_root.glob("*/Toolset.props")) + for path in files: + if path.exists(): + parse_file(path, properties, items, sources) + variables = table(properties) + + def resolved(value): + return resolve(value, variables) + + defines = split_list(resolved(combined(items, "ClCompile", "PreprocessorDefinitions", ";"))) + includes = split_list( + resolved(combined(items, "ClCompile", "AdditionalIncludeDirectories", ";")) + ) + if not includes: + includes = split_list(resolved(variables.get("Console_EndpointIncludeRoot", ""))) + libs = split_list(resolved(combined(items, "Link", "AdditionalLibraryDirectories", ";"))) + if not libs: + libs = split_list(resolved(variables.get("Console_EndpointLibRoot", ""))) + dependencies = split_list( + resolved(combined(items, "Link", "AdditionalDependencies", ";")) + ) + if not dependencies: + dependencies = split_list(resolved(variables.get("Console_Libs", ""))) + + document = { + "sdk": args.sdk, + "platform": directory.name, + "toolset": args.vs, + "root": str(directory), + "sources": sources, + "defines": defines, + "includes": includes, + "libs": libs, + "dependencies": dependencies, + "console": { + "endpoint_include_root": resolved(variables.get("Console_EndpointIncludeRoot", "")), + "endpoint_lib_root": resolved(variables.get("Console_EndpointLibRoot", "")), + "libs": split_list(resolved(variables.get("Console_Libs", ""))), + "tool_path": resolved(variables.get("Console_SdkToolPath", "")), + "sdk_root": resolved(variables.get("Console_SdkRoot", "")), + }, + "flags": { + "additional_options": split_list( + resolved(combined(items, "ClCompile", "AdditionalOptions", " ")) + ), + "ignore_specific_default_libraries": split_list( + resolved(last_item(items, "Link", "IgnoreSpecificDefaultLibraries")) + ), + "runtime_library": resolved(last_item(items, "ClCompile", "RuntimeLibrary")), + "exception_handling": resolved(last_item(items, "ClCompile", "ExceptionHandling")), + "language_standard": resolved(last_item(items, "ClCompile", "LanguageStandard")), + "floating_point_model": resolved( + last_item(items, "ClCompile", "FloatingPointModel") + ), + "enable_enhanced_instruction_set": resolved( + last_item(items, "ClCompile", "EnableEnhancedInstructionSet") + ), + "target_machine": resolved(last_item(items, "Link", "TargetMachine")), + "use_debug_libraries": resolved(variables.get("UseDebugLibraries", "")), + "character_set": resolved(variables.get("CharacterSet", "")), + }, + "properties": { + key: [ + {"value": entry["value"], "condition": entry["condition"], "file": entry["file"]} + for entry in entries + ] + for key, entries in properties.items() + }, + "items": items, + } + Path(args.json).parent.mkdir(parents=True, exist_ok=True) + Path(args.json).write_text(json.dumps(document, indent=2) + "\n", encoding="utf-8") + print( + json.dumps( + { + "platform": document["platform"], + "sources": len(sources), + "defines": len(document["defines"]), + "includes": len(document["includes"]), + "libs": len(document["libs"]), + "dependencies": len(document["dependencies"]), + } + ) + ) + return 0 + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + for name in ("list", "scan"): + command = sub.add_parser(name) + command.add_argument("--root", required=True) + command.add_argument("--vs", default="v170") + command.add_argument("--sdk", default="261000") + if name == "scan": + command.add_argument("--platform", required=True) + command.add_argument("--json", required=True) + command.set_defaults(func=scan_command) + else: + command.set_defaults(func=list_command) + args = parser.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + sys.exit(main()) From 9a5bb201f73940064bb1b7fcfd1f3f34736dc191 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 05:21:54 +0000 Subject: [PATCH 39/44] tooling: report GDK knowledge coverage --- docs/experiments/gdk-knowledge-report.md | 97 + .../python-linux/gdk_knowledge_report.txt | 1 + tests/gdk_knowledge_report_check.py | 467 +++++ tools/gdk_knowledge_report.py | 1676 +++++++++++++++++ 4 files changed, 2241 insertions(+) create mode 100644 docs/experiments/gdk-knowledge-report.md create mode 100644 tests/checks/python-linux/gdk_knowledge_report.txt create mode 100644 tests/gdk_knowledge_report_check.py create mode 100644 tools/gdk_knowledge_report.py diff --git a/docs/experiments/gdk-knowledge-report.md b/docs/experiments/gdk-knowledge-report.md new file mode 100644 index 0000000000..f1aa94cb50 --- /dev/null +++ b/docs/experiments/gdk-knowledge-report.md @@ -0,0 +1,97 @@ +# GDK knowledge coverage report + +tools/gdk_knowledge_report.py merges the JSON knowledge base under +D:\gdk-oracle\knowledge and writes a deterministic coverage JSON and a +Markdown summary. It uses only the Python standard library and never reads a +GDK header, library or binary. + +## Inputs + +All categories are optional. A missing directory or file is reported as a +missing category; it is not treated as an empty fact. + +| Path | Accepted shape | +| --- | --- | +| layouts/*.json | classes array with name, size and members, or a class array | +| abi/*.json | facts array with kind, name and value, or a fact array | +| exports/*.json | exports array with name, ordinal and rva, module groups, or a module map | +| exports-all.json | the same export rows, including the file and kind group form | +| behavior/*.json | observations array, or an observation array | +| platform/*.json | define, include and library lists, plus a flag list or object | +| shaders/corpus.json or shaders/corpus/corpus.json | cases array, or a case array | + +Every fact is normalised to module, kind, name, value, source, confidence and +targets. Layout classes become layout facts whose value contains size and +members; ABI sizeof and struct facts keep their kind. Exports carry their +ordinal and RVA. Runtime observations become behavior facts, and the +observation kind is retained inside the value when it adds information. +Modules are merged case-insensitively. + +A top-level source of msvc-layout, compiled-probe, dumpbin, runtime-oracle or +header-msvc-layout is treated as a method: it becomes the confidence and the +source stays the JSON path. Other source values are kept as given. + +## Conflicts + +The report emits stable value, size, ordinal, enum and type-size entries. Each +entry names the module, the fact, every distinct value with its source, and a +short message. + +- size compares all size-bearing facts for one module and type, including a + layout member list and an ABI sizeof fact. +- type-size compares a named type across modules and reports incompatible + sizes. Equal sizes in two modules are not a conflict. +- ordinal compares only ordinals that both sources report. A missing ordinal + in an import library and a present ordinal in a DLL do not conflict. +- enum compares enum facts with the same module and name. +- value covers every other fact with the same module, kind and name. +- RVAs are retained in the facts but are not compared: Debug, Release, import + library and DLL records legitimately differ. + +MSVC anonymous tags include the text unnamed-tag in their display name. Several +distinct anonymous unions or structs can share that text, so they are kept as +facts and counted as types but excluded from conflict comparisons. Their +display name is not a stable identity. + +## Coverage and shims + +The summary counts modules, unique classes/types, unique exports and raw export +rows, runtime facts, shader facts, platforms and all normalised facts. A +per-module table gives the same breakdown. + +--defs accepts the repository src directory, one .def file, or a JSON mapping. +The parser reads LIBRARY, export names, aliases and ordinals, and ignores +internal x2w_* and X2W* helpers. A shim export is associated when its name or +alias target matches any fact name. The JSON and Markdown list the remaining +exports. + +## Commands + + python -B tests/gdk_knowledge_report_check.py + + $root = 'D:\gdk-oracle\knowledge' + python -B tools/gdk_knowledge_report.py report --root $root --json "$root\coverage.json" --markdown "$root\report.md" --defs src + +Add --check to exit 1 on conflicts. Add --require layouts,abi,exports to also +exit 1 when one of those categories is missing. Bad JSON, a bad schema, an +unknown required category or an unusable path exits 2. Without --check, +missing categories and conflicts are only reported. + +## Measured run + +On 2026-11-28, the local knowledge root produced 44 modules, 11,145 unique +types, 4,714 unique exports from 8,035 export rows, 12 runtime facts, no shader +corpus and 3 platform profiles. The 9,677 ABI sizeof facts matched their layout +sizes, so the conflict list was empty. All 70 GDK-facing shim exports matched +an export fact. The shader category was absent and reported as missing. + +## Limits + +A header fact does not prove the runtime. A layout or ABI row only reports what +the header or compile probe describes. A runtime observation is separate +evidence. An export name proves neither a signature nor a working +implementation, and a shim name match does not prove matching behaviour. The +report intentionally does not compare RVAs, infer missing categories, or turn +an absent oracle into a pass. The generated coverage JSON can be large because +it retains every normalised fact; keep it outside the repository with the rest +of the knowledge base. diff --git a/tests/checks/python-linux/gdk_knowledge_report.txt b/tests/checks/python-linux/gdk_knowledge_report.txt new file mode 100644 index 0000000000..7917575364 --- /dev/null +++ b/tests/checks/python-linux/gdk_knowledge_report.txt @@ -0,0 +1 @@ +tests/gdk_knowledge_report_check.py diff --git a/tests/gdk_knowledge_report_check.py b/tests/gdk_knowledge_report_check.py new file mode 100644 index 0000000000..0e49b43a51 --- /dev/null +++ b/tests/gdk_knowledge_report_check.py @@ -0,0 +1,467 @@ +"""Synthetic controls for the GDK knowledge merge and coverage report.""" + +import json +from pathlib import Path +import subprocess +import sys +import tempfile + + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "gdk_knowledge_report.py" +FACT_FIELDS = {"module", "kind", "name", "value", "source", "confidence", "targets"} + + +def write_json(path, data): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + + +def write_text(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +def make_report_tree(root): + write_json( + root / "layouts" / "alpha.json", + { + "module": "alpha", + "classes": [ + {"name": "Shared", "size": 16, "members": [{"offset": 0, "text": "x"}]}, + {"name": "OnlyA", "size": 8, "members": []}, + {"name": "Cross", "size": 8, "members": []}, + ], + }, + ) + write_json( + root / "layouts" / "beta.json", + {"module": "beta", "classes": [{"name": "Cross", "size": 16, "members": []}]}, + ) + write_json( + root / "abi" / "alpha.json", + { + "module": "alpha", + "facts": [ + {"kind": "sizeof", "name": "Shared", "value": 32}, + {"kind": "struct", "name": "AbiOnly", "value": {"size": 4}}, + {"kind": "enum", "name": "Color", "value": 1}, + {"kind": "constant", "name": "Magic", "value": 1}, + ], + }, + ) + write_json( + root / "abi" / "alpha-more.json", + { + "module": "alpha", + "facts": [ + {"kind": "enum", "name": "Color", "value": 2}, + {"kind": "constant", "name": "Magic", "value": 2}, + ], + }, + ) + write_json( + root / "exports" / "alpha-a.json", + { + "module": "alpha", + "exports": [ + {"name": "Foo", "ordinal": 1, "rva": "0x10"}, + {"name": "Bar", "ordinal": 3, "rva": "0x20"}, + ], + }, + ) + write_json( + root / "exports" / "alpha-b.json", + { + "module": "alpha", + "exports": [ + {"name": "Foo", "ordinal": 2, "rva": "0x30"}, + {"name": "Bar", "ordinal": 3, "rva": "0x20"}, + ], + }, + ) + write_json( + root / "behavior" / "alpha.json", + { + "module": "alpha", + "observations": [ + {"kind": "value", "name": "Bar", "value": 42}, + {"kind": "behavior", "name": "OnlyA", "value": "ok"}, + ], + }, + ) + write_json( + root / "platform" / "windows.json", + { + "platform": "windows-x64", + "defines": ["ALPHA=1"], + "includes": ["alpha.h"], + "libs": ["alpha.lib"], + "flags": ["/W4"], + }, + ) + write_json( + root / "shaders" / "corpus.json", + { + "module": "alpha", + "cases": [ + {"name": "ps-case", "stage": "pixel"}, + {"name": "cs-case", "stage": "compute"}, + ], + }, + ) + write_text( + root / "defs" / "alpha.def", + "LIBRARY alpha\n" + "EXPORTS\n" + " Bar @3\n" + " MissingThing @4\n" + " XMemAllocDefault=Bar @5\n" + " x2w_internal_helper @6\n", + ) + write_json( + root / "defs-map.json", + {"alpha": ["Bar", "MappingOnly", "x2w_mapping_internal"]}, + ) + + +def run_report(root, output, *, defs=None, require=None, check=False, markdown=None): + json_path = Path(output) / "coverage.json" + markdown_path = Path(markdown) if markdown else Path(output) / "report.md" + command = [ + sys.executable, + "-B", + str(TOOL), + "report", + "--root", + str(root), + "--json", + str(json_path), + "--markdown", + str(markdown_path), + ] + if defs is not None: + command.extend(["--defs", str(defs)]) + if require is not None: + command.extend(["--require", require]) + if check: + command.append("--check") + process = subprocess.run(command, capture_output=True, text=True) + return process, json_path, markdown_path + + +def check_report(): + with tempfile.TemporaryDirectory() as temporary: + base = Path(temporary) + root = base / "knowledge" + make_report_tree(root) + + process, json_path, markdown_path = run_report( + root, base / "out", defs=root / "defs" + ) + assert process.returncode == 0, process.stderr + report = json.loads(json_path.read_text(encoding="utf-8")) + markdown = markdown_path.read_text(encoding="utf-8") + + assert report["schema"] == "xbox2windows.gdk_knowledge/1" + assert report["generated_by"] == { + "tool": "gdk_knowledge_report", + "version": 1, + } + assert set(report["categories"]) == { + "layouts", + "abi", + "exports", + "behavior", + "platform", + "shaders", + } + assert all(info["present"] for info in report["categories"].values()) + assert report["missing"] == [] + assert report["required"] == [] + assert report["required_missing"] == [] + + summary = report["summary"] + assert summary["modules"] == 3 + assert summary["types"] == 5 + assert summary["classes_types"] == 5 + assert summary["exports"] == 2 + assert summary["export_rows"] == 4 + assert summary["runtime_facts"] == 2 + assert summary["shader_facts"] == 2 + assert summary["platforms"] == 1 + assert summary["facts"] == 19 + assert summary["conflicts"] == 5 + assert summary["shims"] == 3 + assert summary["shims_without_fact"] == 1 + assert report["categories"]["layouts"]["facts"] == 4 + assert report["categories"]["abi"]["facts"] == 6 + assert report["categories"]["exports"]["facts"] == 4 + + assert len(report["facts"]) == 19 + for fact in report["facts"]: + assert set(fact) == FACT_FIELDS + assert fact["module"] + assert fact["kind"] + assert fact["name"] + assert isinstance(fact["confidence"], str) + assert isinstance(fact["targets"], list) + assert not str(fact["source"]).startswith(str(base)) + assert report["facts"] == sorted( + report["facts"], + key=lambda fact: ( + fact["module"].casefold(), + fact["module"], + fact["kind"].casefold(), + fact["kind"], + fact["name"].casefold(), + fact["name"], + json.dumps( + fact["value"], sort_keys=True, ensure_ascii=False, separators=(",", ":") + ), + json.dumps( + fact["source"], sort_keys=True, ensure_ascii=False, separators=(",", ":") + ), + ), + ) + + shared = next( + fact + for fact in report["facts"] + if fact["module"] == "alpha" + and fact["kind"] == "layout" + and fact["name"] == "Shared" + ) + assert shared["value"] == { + "size": 16, + "members": [{"offset": 0, "text": "x"}], + } + assert shared["source"] == "layouts/alpha.json" + assert shared["confidence"] == "header" + + behavior = next( + fact + for fact in report["facts"] + if fact["name"] == "Bar" and fact["kind"] == "behavior" + ) + assert behavior["value"] == 42 + assert behavior["confidence"] == "runtime" + + kinds = [conflict["kind"] for conflict in report["conflicts"]] + assert kinds == ["value", "size", "ordinal", "enum", "type-size"], kinds + by_kind = {conflict["kind"]: conflict for conflict in report["conflicts"]} + assert by_kind["size"]["module"] == "alpha" + assert by_kind["size"]["name"] == "Shared" + assert {item["value"] for item in by_kind["size"]["values"]} == {16, 32} + assert by_kind["ordinal"]["module"] == "alpha" + assert by_kind["ordinal"]["name"] == "Foo" + assert [item["value"] for item in by_kind["ordinal"]["values"]] == [1, 2] + assert by_kind["enum"]["name"] == "Color" + assert {item["value"] for item in by_kind["enum"]["values"]} == {1, 2} + assert by_kind["type-size"]["name"] == "Cross" + assert by_kind["type-size"]["modules"] == ["alpha", "beta"] + assert {item["module"] for item in by_kind["type-size"]["values"]} == {"alpha", "beta"} + assert by_kind["value"]["name"] == "Magic" + for conflict in report["conflicts"]: + assert conflict["message"] + assert conflict["sources"] == sorted(set(conflict["sources"])) + + shims = report["shims"] + assert shims["exports"] == 3 + assert shims["covered"] == 2 + assert shims["internal"] == 1 + assert [ + (item["module"], item["name"], item["alias"]) + for item in shims["without_fact"] + ] == [("alpha", "MissingThing", None)] + + modules = {module["module"]: module for module in report["modules"]} + assert set(modules) == {"alpha", "beta", "windows-x64"} + assert modules["alpha"]["types"] == 4 + assert modules["alpha"]["exports"] == 2 + assert modules["alpha"]["runtime_facts"] == 2 + assert modules["alpha"]["shader_facts"] == 2 + assert modules["windows-x64"]["platform_facts"] == 1 + + assert markdown.startswith("# GDK knowledge coverage\n") + assert "| Modules | 3 |" in markdown + assert "| Classes/types | 5 |" in markdown + assert "| Runtime facts | 2 |" in markdown + assert "| Conflicts | 5 |" in markdown + assert "| ordinal | alpha | Foo |" in markdown + assert "MissingThing" in markdown + assert "A header fact does not prove the runtime." in markdown + assert markdown.endswith("\n") and not markdown.endswith("\n\n") + + second_process, second_json, second_markdown = run_report( + root, base / "out-again", defs=root / "defs" + ) + assert second_process.returncode == 0, second_process.stderr + assert json_path.read_bytes() == second_json.read_bytes() + assert markdown_path.read_bytes() == second_markdown.read_bytes() + + mapping_process, mapping_json, _ = run_report( + root, base / "out-mapping", defs=root / "defs-map.json" + ) + assert mapping_process.returncode == 0, mapping_process.stderr + mapping_report = json.loads(mapping_json.read_text(encoding="utf-8")) + assert mapping_report["summary"]["shims"] == 2 + assert mapping_report["summary"]["shims_without_fact"] == 1 + assert [ + (item["module"], item["name"]) + for item in mapping_report["shims"]["without_fact"] + ] == [("alpha", "MappingOnly")] + assert mapping_report["shims"]["internal"] == 1 + + checked, checked_json, checked_markdown = run_report( + root, base / "out-check", defs=root / "defs", check=True + ) + assert checked.returncode == 1 + assert checked_json.is_file() + assert checked_markdown.is_file() + assert "conflict" in checked.stderr + + +def check_require(): + with tempfile.TemporaryDirectory() as temporary: + base = Path(temporary) + root = base / "clean" + write_json( + root / "layouts" / "one.json", + {"module": "one", "classes": [{"name": "Only", "size": 4, "members": []}]}, + ) + + passed, passed_json, _ = run_report( + root, base / "out-pass", require="layouts", check=True + ) + assert passed.returncode == 0, passed.stderr + passed_report = json.loads(passed_json.read_text(encoding="utf-8")) + assert passed_report["required"] == ["layouts"] + assert passed_report["required_missing"] == [] + assert passed_report["missing"] == ["abi", "exports", "behavior", "platform", "shaders"] + + failed, failed_json, failed_markdown = run_report( + root, base / "out-fail", require="layouts,exports", check=True + ) + assert failed.returncode == 1 + assert "exports" in failed.stderr + failed_report = json.loads(failed_json.read_text(encoding="utf-8")) + assert failed_report["required"] == ["layouts", "exports"] + assert failed_report["required_missing"] == ["exports"] + assert "Required categories missing: exports." in failed_markdown.read_text( + encoding="utf-8" + ) + + warned, warned_json, warned_markdown = run_report( + root, base / "out-warn", require="exports" + ) + assert warned.returncode == 0, warned.stderr + warned_report = json.loads(warned_json.read_text(encoding="utf-8")) + assert warned_report["required_missing"] == ["exports"] + assert "Required categories missing: exports." in warned_markdown.read_text( + encoding="utf-8" + ) + + +def check_module_case(): + with tempfile.TemporaryDirectory() as temporary: + base = Path(temporary) + root = base / "case" + write_json( + root / "layouts" / "one.json", + {"module": "Alpha", "classes": [{"name": "One", "size": 4, "members": []}]}, + ) + write_json( + root / "layouts" / "two.json", + {"module": "alpha", "classes": [{"name": "Two", "size": 8, "members": []}]}, + ) + process, json_path, _ = run_report(root, base / "out") + assert process.returncode == 0, process.stderr + report = json.loads(json_path.read_text(encoding="utf-8")) + assert [module["module"] for module in report["modules"]] == ["alpha"] + assert report["modules"][0]["types"] == 2 + assert report["summary"]["modules"] == 1 + + +def check_errors(): + with tempfile.TemporaryDirectory() as temporary: + base = Path(temporary) + + missing_root, _, _ = run_report(base / "absent", base / "out-absent") + assert missing_root.returncode == 2 + assert "does not exist" in missing_root.stderr + + malformed = base / "malformed" + write_text(malformed / "layouts" / "bad.json", "{") + malformed_process, _, _ = run_report(malformed, base / "out-malformed") + assert malformed_process.returncode == 2 + assert "invalid JSON" in malformed_process.stderr + + wrong_shape = base / "wrong-shape" + write_json(wrong_shape / "layouts" / "bad.json", {"classes": {}}) + wrong_process, _, _ = run_report(wrong_shape, base / "out-wrong") + assert wrong_process.returncode == 2 + assert "classes" in wrong_process.stderr + + valid = base / "valid" + write_json( + valid / "layouts" / "one.json", + {"module": "one", "classes": [{"name": "Only", "size": 4, "members": []}]}, + ) + unknown_require, _, _ = run_report( + valid, base / "out-unknown", require="layouts,unknown" + ) + assert unknown_require.returncode == 2 + assert "unknown category" in unknown_require.stderr + + absent_defs, _, _ = run_report( + valid, base / "out-defs", defs=base / "absent-defs" + ) + assert absent_defs.returncode == 2 + assert "does not exist" in absent_defs.stderr + + bad_mapping = base / "bad-mapping.json" + write_text(bad_mapping, "[") + bad_mapping_process, _, _ = run_report( + valid, base / "out-map", defs=bad_mapping + ) + assert bad_mapping_process.returncode == 2 + assert "invalid JSON" in bad_mapping_process.stderr + + same_path = base / "same.md" + same_process, _, _ = run_report( + valid, base / "out-same", markdown=same_path + ) + assert same_process.returncode == 0, same_process.stderr + + json_path = base / "collision.json" + collision = subprocess.run( + [ + sys.executable, + "-B", + str(TOOL), + "report", + "--root", + str(valid), + "--json", + str(json_path), + "--markdown", + str(json_path), + ], + capture_output=True, + text=True, + ) + assert collision.returncode == 2 + assert "different paths" in collision.stderr + + +def main(): + check_report() + check_require() + check_module_case() + check_errors() + print("gdk_knowledge_report_check: ok") + + +if __name__ == "__main__": + main() diff --git a/tools/gdk_knowledge_report.py b/tools/gdk_knowledge_report.py new file mode 100644 index 0000000000..33e9b17935 --- /dev/null +++ b/tools/gdk_knowledge_report.py @@ -0,0 +1,1676 @@ +#!/usr/bin/env python3 +"""Merge GDK knowledge facts, report conflicts and count coverage. + +The tool reads only JSON metadata. It never loads a GDK binary, header or SDK +file. Inputs are optional directories under a knowledge root: + + layouts/*.json layout classes with a size and members + abi/*.json ABI facts (structs, enums, constants, GUIDs) + exports/*.json export rows, or a root exports-all.json + behavior/*.json runtime observations + platform/*.json build defines, includes, libraries and flags + shaders/corpus.json shader corpus cases + +Normalised facts carry module, kind, name, value, source, confidence and +targets. Conflicts are grouped by fact identity and by type name. The report is +deterministic: facts, conflicts, modules and shims are sorted before writing. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import re +import sys +from collections import defaultdict + + +SCHEMA = "xbox2windows.gdk_knowledge/1" +TOOL = "gdk_knowledge_report" +VERSION = 1 +CATEGORIES = ("layouts", "abi", "exports", "behavior", "platform", "shaders") +TYPE_KINDS = frozenset( + {"layout", "class", "struct", "union", "type", "typedef", "sizeof"} +) +ENUM_KINDS = frozenset({"enum", "enumerator", "enumeration", "enum-value"}) +CONFLICT_ORDER = {"value": 0, "size": 1, "ordinal": 2, "enum": 3, "type-size": 4} +FACT_FIELDS = ("module", "kind", "name", "value", "source", "confidence", "targets") +DEFAULT_CONFIDENCE = { + "layouts": "header", + "abi": "compiled", + "exports": "export-table", + "behavior": "runtime", + "platform": "build-profile", + "shaders": "shader-corpus", +} +LEFTOVER_KEYS = frozenset( + {"module", "kind", "name", "value", "source", "confidence", "targets"} +) +METHOD_SOURCES = frozenset( + { + "msvc-layout", + "compiled-probe", + "dumpbin", + "runtime-oracle", + "header-msvc-layout", + } +) + + +class InputError(Exception): + """A malformed input or unusable path. The CLI maps this to exit code 2.""" + + +def _canonical(value): + return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + + +def _as_int(value): + if isinstance(value, bool) or value is None: + return None + if isinstance(value, int): + return value + if isinstance(value, str): + text = value.strip() + if not text: + return None + try: + if text.lower().startswith(("0x", "-0x")): + return int(text, 16) + return int(text, 10) + except ValueError: + return None + return None + + +def _display_source(source): + if isinstance(source, str): + return source + return _canonical(source) + + +def _value_sort_key(value): + if isinstance(value, bool): + return (0, int(value), "") + if isinstance(value, (int, float)): + return (1, value, "") + if isinstance(value, str): + return (2, 0, value) + return (3, 0, _canonical(value)) + + +def _relative(path, root): + path = Path(path) + root = Path(root) + try: + return path.resolve().relative_to(root.resolve()).as_posix() + except (OSError, ValueError): + return path.name + + +def _read_json(path): + path = Path(path) + try: + text = path.read_text(encoding="utf-8-sig") + except OSError as exc: + raise InputError("cannot read {}: {}".format(path, exc)) from exc + try: + return json.loads(text) + except json.JSONDecodeError as exc: + raise InputError( + "invalid JSON in {} at line {} column {}: {}".format( + path, exc.lineno, exc.colno, exc.msg + ) + ) from exc + + +def _require_object(value, where): + if not isinstance(value, dict): + raise InputError("{} must be a JSON object".format(where)) + return value + + +def _require_list(value, where): + if not isinstance(value, list): + raise InputError("{} must be a JSON array".format(where)) + return value + + +def _require_name(item, where, keys=("name",)): + for key in keys: + value = item.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + raise InputError("{} has no non-empty {}".format(where, "/".join(keys))) + + +def _normalise_targets(value, where): + if value is None: + return [] + if isinstance(value, str): + return [value] + if not isinstance(value, list): + raise InputError("{} targets must be a string or an array".format(where)) + targets = [] + for target in value: + if not isinstance(target, str): + raise InputError("{} targets must contain strings".format(where)) + if target: + targets.append(target) + return sorted(set(targets)) + + +def _source_and_confidence(item, meta, default_source, default_confidence): + item = item if isinstance(item, dict) else {} + meta = meta if isinstance(meta, dict) else {} + source = None + method = None + for candidate in (item.get("source"), meta.get("source")): + if isinstance(candidate, str) and candidate.strip(): + text = candidate.strip() + if text.casefold() in METHOD_SOURCES: + if method is None: + method = text + elif source is None: + source = text + elif candidate is not None and source is None: + source = candidate + confidence = ( + item.get("confidence") + or meta.get("confidence") + or method + or default_confidence + ) + return source or default_source, confidence + + +def _module_from_stem(stem): + text = Path(stem).stem + lowered = text.casefold() + suffixes = ( + "-all-layout", + "-interesting-layout", + "-layout-report", + "-layout", + "_layout", + "-vtables", + "-facts", + "-exports", + ) + for suffix in suffixes: + if lowered.endswith(suffix) and len(text) > len(suffix): + return text[: -len(suffix)] + return text + + +def _module_from_library(path): + name = Path(path).name + lowered = name.casefold() + for suffix in (".lib", ".dll"): + if lowered.endswith(suffix): + return name[: -len(suffix)] + return _module_from_stem(name) + + +def _module_from_def_stem(stem): + module = _module_from_stem(stem) + lowered = module.casefold() + for suffix in ("_shim", "-shim"): + if lowered.endswith(suffix) and len(module) > len(suffix): + return module[: -len(suffix)] + return module + + +def _make_fact(module, kind, name, value, source, confidence, targets): + if not isinstance(module, str) or not module.strip(): + raise InputError("fact {} has no module".format(name)) + if not isinstance(kind, str) or not kind.strip(): + raise InputError("fact {} has no kind".format(name)) + if not isinstance(name, str) or not name.strip(): + raise InputError("fact has no non-empty name") + if confidence is None: + confidence = "" + if not isinstance(confidence, str): + confidence = str(confidence) + return { + "module": module.strip(), + "kind": kind.strip(), + "name": name.strip(), + "value": value, + "source": source, + "confidence": confidence, + "targets": list(targets), + } + + +def _fact_sort_key(fact): + return ( + fact["module"].casefold(), + fact["module"], + fact["kind"].casefold(), + fact["kind"], + fact["name"].casefold(), + fact["name"], + _canonical(fact["value"]), + _canonical(fact["source"]), + ) + + +def _dedupe_facts(facts): + seen = set() + result = [] + for fact in facts: + key = _canonical(fact) + if key in seen: + continue + seen.add(key) + result.append(fact) + result.sort(key=_fact_sort_key) + return result + + +def _canonicalise_modules(facts): + counts = defaultdict(lambda: defaultdict(int)) + for fact in facts: + counts[fact["module"].casefold()][fact["module"]] += 1 + canonical = {} + for key, variants in counts.items(): + if len(variants) == 1: + canonical[key] = next(iter(variants)) + continue + canonical[key] = sorted( + variants, + key=lambda name: ( + -variants[name], + name != name.lower(), + name.casefold(), + name, + ), + )[0] + for fact in facts: + fact["module"] = canonical[fact["module"].casefold()] + return facts + + +def _is_type_kind(kind): + return kind.casefold() in TYPE_KINDS + + +def _is_enum_kind(kind): + lowered = kind.casefold().replace("_", "-") + return lowered in ENUM_KINDS or lowered.startswith("enum-") + + +def _is_anonymous_name(name): + lowered = name.casefold() + return " 160: + shown = shown[:157] + "..." + parts.append( + "{}={} ({})".format( + item.get("module", ""), + shown, + _md_cell(item.get("source", "")), + ) + ) + return "; ".join(parts) + + +def render_markdown(report): + summary = report["summary"] + lines = [ + "# GDK knowledge coverage", + "", + "- Schema: {}".format(report["schema"]), + "- Tool: {} version {}".format( + report["generated_by"]["tool"], report["generated_by"]["version"] + ), + "- Knowledge root: {}".format(_md_cell(report["inputs"]["root"])), + "", + "The report merges metadata facts from the knowledge root. It does not read", + "or execute SDK binaries, and it does not infer a fact from a missing category.", + "", + "## Summary", + "", + "| Metric | Value |", + "| --- | ---: |", + "| Modules | {} |".format(summary["modules"]), + "| Classes/types | {} |".format(summary["types"]), + "| Exports | {} |".format(summary["exports"]), + "| Export rows | {} |".format(summary["export_rows"]), + "| Runtime facts | {} |".format(summary["runtime_facts"]), + "| Shader facts | {} |".format(summary["shader_facts"]), + "| Platforms | {} |".format(summary["platforms"]), + "| Normalised facts | {} |".format(summary["facts"]), + "| Conflicts | {} |".format(summary["conflicts"]), + "| Shim exports | {} |".format(summary["shims"]), + "| Shims without fact | {} |".format(summary["shims_without_fact"]), + "", + "## Categories", + "", + "| Category | State | Files | Facts |", + "| --- | --- | ---: | ---: |", + ] + for category in CATEGORIES: + info = report["categories"][category] + files = ", ".join(info["files"]) if info["files"] else "-" + lines.append( + "| {} | {} | {} | {} |".format( + category, + "present" if info["present"] else "missing", + _md_cell(files), + info["facts"], + ) + ) + lines.append("") + if report["missing"]: + lines.append( + "Missing categories: {}.".format(", ".join(report["missing"])) + ) + else: + lines.append("All six categories are present.") + if report["required"]: + if report["required_missing"]: + lines.append( + "Required categories missing: {}.".format( + ", ".join(report["required_missing"]) + ) + ) + else: + lines.append( + "Required categories present: {}.".format( + ", ".join(report["required"]) + ) + ) + + lines.extend(["", "## Conflicts", ""]) + if report["conflicts"]: + lines.extend( + [ + "| Kind | Module | Name | Values | Sources |", + "| --- | --- | --- | --- | --- |", + ] + ) + for conflict in report["conflicts"]: + lines.append( + "| {} | {} | {} | {} | {} |".format( + conflict["kind"], + _md_cell(conflict["module"]), + _md_cell(conflict["name"]), + _md_cell(_md_values(conflict["values"])), + _md_cell(", ".join(conflict["sources"])), + ) + ) + else: + lines.append("No conflicts detected.") + + lines.extend( + [ + "", + "## Coverage by module", + "", + "| Module | Classes/types | Exports | Runtime facts | Shader facts | Platform facts | Facts |", + "| --- | ---: | ---: | ---: | ---: | ---: | ---: |", + ] + ) + for module in report["modules"]: + lines.append( + "| {} | {} | {} | {} | {} | {} | {} |".format( + _md_cell(module["module"]), + module["types"], + module["exports"], + module["runtime_facts"], + module["shader_facts"], + module["platform_facts"], + module["facts"], + ) + ) + + lines.extend(["", "## Shims without associated fact", ""]) + if report["inputs"]["defs"] is None: + lines.append("Shim coverage was not checked; pass --defs or a mapping JSON.") + elif report["shims"]["without_fact"]: + lines.extend( + [ + "| Module | Shim export | Alias | Def |", + "| --- | --- | --- | --- |", + ] + ) + for shim in report["shims"]["without_fact"]: + lines.append( + "| {} | {} | {} | {} |".format( + _md_cell(shim["module"]), + _md_cell(shim["name"]), + _md_cell(shim["alias"] or "-"), + _md_cell(shim["source"]), + ) + ) + else: + lines.append( + "All {} shim exports match a fact.".format(report["shims"]["exports"]) + ) + + lines.extend( + [ + "", + "## Limits", + "", + "A header fact does not prove the runtime. Layout and ABI rows only describe", + "the header or compile-time probe that produced them; runtime observations are", + "separate facts with their own source and confidence. An absent category is", + "reported as missing and is not treated as a zero-valued fact. Ordinals are", + "compared only when both sources report one, and RVA differences between", + "debug, release, import-library and DLL records are not conflicts. Anonymous", + "MSVC tags are counted as types but are not compared by display name because", + "several distinct anonymous records can share the same text.", + ] + ) + return "\n".join(lines) + "\n" + + +def _write_text(path, text): + path = Path(path) + try: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + except OSError as exc: + raise InputError("cannot write {}: {}".format(path, exc)) from exc + + +def _parse_required(value): + if value is None: + return [] + result = [] + for token in value.split(","): + category = token.strip().casefold() + if not category: + raise InputError("--require contains an empty category") + if category not in CATEGORIES: + raise InputError( + "--require has unknown category {}; expected one of {}".format( + category, ", ".join(CATEGORIES) + ) + ) + if category not in result: + result.append(category) + return result + + +def _run_report(args): + root = Path(args.root) + json_path = Path(args.json) + markdown_path = Path(args.markdown) + if json_path.resolve() == markdown_path.resolve(): + raise InputError("--json and --markdown must be different paths") + required = _parse_required(args.require) + report = build_report(root, args.defs, required) + + _write_text( + json_path, + json.dumps(report, indent=2, sort_keys=True, ensure_ascii=False) + "\n", + ) + _write_text(markdown_path, render_markdown(report)) + + summary = report["summary"] + print( + "{}: {} facts, {} conflicts, {} shims without fact".format( + TOOL, + summary["facts"], + summary["conflicts"], + summary["shims_without_fact"], + ) + ) + + if args.check: + failures = [] + if report["conflicts"]: + failures.append("{} conflict(s)".format(len(report["conflicts"]))) + if report["required_missing"]: + failures.append( + "missing required categories: {}".format( + ", ".join(report["required_missing"]) + ) + ) + if failures: + print("error: " + "; ".join(failures), file=sys.stderr) + return 1 + return 0 + + +def _build_parser(): + parser = argparse.ArgumentParser( + description="Merge GDK knowledge facts and report coverage and conflicts." + ) + subparsers = parser.add_subparsers(dest="command", required=True) + report = subparsers.add_parser("report", help="write coverage JSON and Markdown") + report.add_argument("--root", required=True, help="knowledge root directory") + report.add_argument("--json", required=True, help="coverage JSON output") + report.add_argument("--markdown", required=True, help="Markdown report output") + report.add_argument( + "--defs", + help="repository src directory, one .def file, or a shim-mapping JSON", + ) + report.add_argument( + "--require", + help="comma-separated categories that must be present (with --check)", + ) + report.add_argument( + "--check", + action="store_true", + help="exit 1 on conflicts or missing categories listed by --require", + ) + return parser + + +def main(argv=None): + parser = _build_parser() + args = parser.parse_args(argv) + try: + if args.command == "report": + return _run_report(args) + parser.error("unknown command") + except InputError as exc: + print("error: {}".format(exc), file=sys.stderr) + return 2 + return 2 + + +if __name__ == "__main__": + sys.exit(main()) From 789ee5739541423af1659f45d6862f4817e388da Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 05:27:08 +0000 Subject: [PATCH 40/44] ci: retry the Windows smoke test From 4b833b23f2931ed333b6beee86bae82636007bb8 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 05:29:47 +0000 Subject: [PATCH 41/44] tooling: keep print-only ABI probes to size facts --- tests/gdk_layouts_check.py | 18 ++++++++++++++++++ tools/gdk_abi_probe.py | 9 +++++---- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/tests/gdk_layouts_check.py b/tests/gdk_layouts_check.py index ea57062b3f..3d584e2771 100644 --- a/tests/gdk_layouts_check.py +++ b/tests/gdk_layouts_check.py @@ -144,6 +144,24 @@ def check_probe(): check("offsetof(Derived, C)" not in text, "base-class offset emitted") check('std::printf("offsetof(Simple, B)=%zu\\n", offsetof(Simple, B));' in text, "print B") + size_only = directory / "size-only.cpp" + private_classes = classes + [ + {"name": "PrivateField", "size": 4, "bases": [], "members": [ + {"offset": 0, "type": "int", "name": "hidden", "bits": None, "kind": "field"}, + ]}, + ] + private_layout = directory / "private.json" + write_layouts(private_layout, private_classes) + code = abi.main([ + "generate", "--layouts", str(private_layout), "--out", str(size_only), + "--include", "synthetic.h", "--print", + ]) + check(code == 0, f"size-only generate exit {code}") + size_text = size_only.read_text(encoding="utf-8") + check('std::printf("sizeof(PrivateField)=%zu\\n"' in size_text, "size-only sizeof") + check("offsetof(PrivateField, hidden)" not in size_text, "print-only emitted offsetof") + check('std::printf("offsetof(Simple, B)=%zu\\n"' not in size_text, "print-only emitted a public offsetof") + log = directory / "probe.log" log.write_text("sizeof(Simple)=12\noffsetof(Simple, A)=0\n", encoding="utf-8") parsed = directory / "parsed.json" diff --git a/tools/gdk_abi_probe.py b/tools/gdk_abi_probe.py index a16e8474af..656a9f06f9 100644 --- a/tools/gdk_abi_probe.py +++ b/tools/gdk_abi_probe.py @@ -78,10 +78,11 @@ def generate_command(args): for block in classes: name = block["name"] lines.append(f' std::printf("sizeof({name})=%zu\\n", sizeof({name}));') - for member, _ in member_offsets(block): - lines.append( - f' std::printf("offsetof({name}, {member})=%zu\\n", offsetof({name}, {member}));' - ) + if args.offsetof: + for member, _ in member_offsets(block): + lines.append( + f' std::printf("offsetof({name}, {member})=%zu\\n", offsetof({name}, {member}));' + ) lines += [" return 0;", "}"] Path(args.out).parent.mkdir(parents=True, exist_ok=True) Path(args.out).write_text("\n".join(lines) + "\n", encoding="utf-8") From 354b32ffc4ccee8209ea7c1279e4d322533e471b Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 05:57:22 +0000 Subject: [PATCH 42/44] tooling: use the selected SDK for platform paths --- docs/experiments/gdk-platform-profiles.md | 5 ++++ tests/gdk_platform_profiles_check.py | 30 +++++++++++++++++++++++ tools/gdk_platform_profiles.py | 23 +++++++++++------ 3 files changed, 51 insertions(+), 7 deletions(-) diff --git a/docs/experiments/gdk-platform-profiles.md b/docs/experiments/gdk-platform-profiles.md index ac480fab28..1f25a1fb20 100644 --- a/docs/experiments/gdk-platform-profiles.md +++ b/docs/experiments/gdk-platform-profiles.md @@ -13,6 +13,11 @@ The GDK installation and the JSON profiles stay outside the repository. python -B tools/gdk_platform_profiles.py list --root D:\gdk-ref\261000\gxdk\Microsoft GDK\261000\GXDK python -B tools/gdk_platform_profiles.py scan --root D:\gdk-ref\261000\gxdk\Microsoft GDK\261000\GXDK --platform Gaming.Xbox.Scarlett.x64 --json out\scarlett.json +The --sdk option selects the versioned subdirectory (261000, 999999, ...). A +platform directory without that subdirectory is rejected before any output is +written, so the reported SDK, the source paths and the extracted values always +refer to the same edition. + Measured on 28 November 2026 from the 261000 payload: | Platform | Sources | Defines | Includes | Libs | Dependencies | diff --git a/tests/gdk_platform_profiles_check.py b/tests/gdk_platform_profiles_check.py index 5411d37370..1049b3e3d9 100644 --- a/tests/gdk_platform_profiles_check.py +++ b/tests/gdk_platform_profiles_check.py @@ -69,6 +69,14 @@ def make_tree(root): MultiThreadedDLL + """, + ) + write( + platform / "999999" / "Platform.Common.props", + """ + + PROFILE_999999 + """, ) return platform @@ -110,6 +118,28 @@ def main(): check(conditions[0]["condition"] == "'$(Configuration)'=='Debug'", f"condition {conditions}") check(len(document["sources"]) == 4, f"sources {len(document['sources'])}") + other_output = root / "profile-999999.json" + other = profiles.main([ + "scan", "--root", str(root), "--platform", "Gaming.Xbox.Scarlett.x64", + "--sdk", "999999", "--json", str(other_output), + ]) + check(other == 0, f"999999 scan exit {other}") + other_document = json.loads(other_output.read_text(encoding="utf-8")) + check(other_document["sdk"] == "999999", f"sdk {other_document['sdk']}") + check(other_document["defines"] == ["PROFILE_999999"], f"defines {other_document['defines']}") + source_paths = [item["path"] for item in other_document["sources"]] + check(any("999999" in path and "Platform.Common.props" in path for path in source_paths), + f"999999 source {source_paths}") + check(not any("261000" in path for path in source_paths), f"261000 leaked {source_paths}") + + unsupported_output = root / "profile-unsupported.json" + unsupported = profiles.main([ + "scan", "--root", str(root), "--platform", "Gaming.Xbox.Scarlett.x64", + "--sdk", "888888", "--json", str(unsupported_output), + ]) + check(unsupported == 2, f"unsupported SDK exit {unsupported}") + check(not unsupported_output.exists(), "unsupported SDK wrote output") + missing = profiles.main([ "scan", "--root", str(root), "--platform", "Gaming.Desktop.x64", "--json", str(root / "missing.json"), diff --git a/tools/gdk_platform_profiles.py b/tools/gdk_platform_profiles.py index 8091133008..0bc98d22dc 100644 --- a/tools/gdk_platform_profiles.py +++ b/tools/gdk_platform_profiles.py @@ -55,6 +55,8 @@ def score(directory, vs, sdk): value += 5 if sdk in parts: value += 3 + if (directory / sdk).is_dir(): + value += 15 return value @@ -62,7 +64,10 @@ def choose(root, platform, vs, sdk): matches = [item for item in platform_dirs(root) if item.name.lower() == platform.lower()] if not matches: return None - return max(matches, key=lambda item: (score(item, vs, sdk), -len(str(item)))) + versioned = [item for item in matches if (item / sdk).is_dir()] + if not versioned: + return None + return max(versioned, key=lambda item: (score(item, vs, sdk), -len(str(item)))) def list_command(args): @@ -173,18 +178,22 @@ def combined(items, group, key, separator): def scan_command(args): directory = choose(args.root, args.platform, args.vs, args.sdk) if directory is None: - print(f"platform not found: {args.platform}", file=sys.stderr) + print( + f"platform not found for SDK {args.sdk}: {args.platform}", + file=sys.stderr, + ) return 2 sources = [] properties = {} items = {} + edition = directory / args.sdk files = [ directory / "Platform.default.props", - directory / "261000" / "Platform.Common.props", - directory / "261000" / "Platform.Edition.default.props", - directory / "261000" / "Platform.Edition.props", - directory / "261000" / "Platform.Edition.targets", - directory / "261000" / "Platform.Commandline.targets", + edition / "Platform.Common.props", + edition / "Platform.Edition.default.props", + edition / "Platform.Edition.props", + edition / "Platform.Edition.targets", + edition / "Platform.Commandline.targets", directory / "Platform.props", directory / "Platform.targets", ] From c6c7688bf97979b9d94b35cecaf9c190b2d90eb7 Mon Sep 17 00:00:00 2001 From: wish131400 <2898869317@qq.com> Date: Sat, 28 Nov 2026 18:18:39 +0800 Subject: [PATCH 43/44] runtime: restore bounded native scalar windows in integration --- .../native-scalar-window-integration.md | 71 +++++++++++++++++++ src/startup_stubs/d3d12_compute_dispatch.inl | 17 ++++- 2 files changed, 87 insertions(+), 1 deletion(-) create mode 100644 docs/experiments/native-scalar-window-integration.md diff --git a/docs/experiments/native-scalar-window-integration.md b/docs/experiments/native-scalar-window-integration.md new file mode 100644 index 0000000000..0a04893969 --- /dev/null +++ b/docs/experiments/native-scalar-window-integration.md @@ -0,0 +1,71 @@ +# Native scalar input windows in the integration stack + +The public integration stack in [#3248](https://github.com/R0Y00/Xbox2Windows/pull/3248), +at `7f97cb5ba467d16019dfd3ecdc86cf09c6dbcf09`, retains the native compiler's +`Slot::scalar_window` metadata but does not consume it when resolving compute inputs. +The bounded unplaced-window fallback exists in the public runtime branch of +[#3094](https://github.com/R0Y00/Xbox2Windows/pull/3094) at `97cde4d5`. + +## Reproduction and change + +The existing source-built +[native compute dispatch check](../../tests/startup_compute_dispatch_native_check.py) +loads its scalar descriptor from table 1 byte 64 and reads a scalar at buffer byte 36. +The descriptor has three records of stride 16 in readable CPU memory outside the +fixture's placed buffers. A valid decoy at table byte 0 contains a different value. + +On the unmodified integration head, the first positive case is refused with +`an input is in title memory outside any placed buffer`. All 288 result words stay +at `0xc5c5c5c5` instead of becoming `0x400`; the 32 guard words remain untouched. +Native translation itself succeeds. + +Restore the bounded fallback after normal GPU-backed range resolution. It applies +only to native scalar views, non-token descriptors, and that specific unplaced-range +refusal. The descriptor must cover the compiler's required bytes, contain whole +dwords, be at most 64 KiB, and be completely readable. The existing frame upload +copy retains the data for the recording. Successful normal resolution, invalid +tokens, partial placements and short windows do not enter this fallback. Existing +compute input source counters identify the fallback as a CPU snapshot. + +This restores integration behavior; it does not enable the separate opt-in snapshot +of non-aliased placed buffers and does not change that policy. + +## Validation + +Windows 10 Pro build 19045, NVIDIA GeForce RTX 4070 Ti SUPER, driver +`32.0.15.7270`, Release `/O2`, MSVC `19.43.34810`, DXC `1.9.2609`, +Agility SDK 620, D3D12 debug layer enabled. The local WARP driver is +`10.0.19041.5794`. + +```powershell +. .\tools\dev.ps1 +cmake --build --preset runtime +# Use Windows' locale encoding for localized native error messages in this fixture. +$env:PYTHONUTF8 = '0' +ctest --preset release --no-tests=error -j 1 -V -R '^(native_fixed_mesh57_(varying|buffers)?_?hardware|startup_native_graphics_draw_hardware|startup_compute_dispatch_(native|input)_hardware|startup_slot67_indirect_dispatch_hardware)$' +ctest --preset release --no-tests=error -j 1 -V -R '^(startup_compute_dispatch_(native|input)|startup_slot67_indirect_dispatch)_warp$' +``` + +- Hardware: 7 selected, 7 passed, 0 failed, 0 skipped, 24.09 seconds. +- The scalar positives match all 288 result words for both `0x400` and `0x45678`, + with all 32 guards unchanged. The two-record (32-byte) control is refused and + leaves the complete output unchanged. The ordinary native, published fallback, + wrong table and shared read/write UAV cases also pass. +- Existing input rejection, opt-in snapshot, memory-view token, indirect dispatch + and fixed Mesh pixel checks pass without changing their assertions. +- WARP: 3 selected, 2 passed, 0 failed, 1 capability skip, 7.24 seconds. Native + compute skips because this WARP adapter has no 32-lane waves; its published + fallback and refusal controls run before the skip. + +With Python 3.14's UTF-8 default, the graphics check separately fails decoding a +localized missing-DXC error. `PYTHONUTF8=0` permits its existing negative control +to run; no graphics or test source change was needed for that local encoding issue. + +## Scope + +This fixture uses only synthetic inputs. Its descriptor shape is relevant to +[#3310](https://github.com/R0Y00/Xbox2Windows/issues/3310), but it does not establish +the cause of that issue's 48 zero argument records. A matched integration capture +must still identify the actual SRV producer, demonstrate nonzero matching +post-write and pre-consume records at the same resource and offset, and show a real +Mesh submission changing scene color before composition. diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 4521088991..057ed58ffc 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -721,7 +721,22 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& } if (!output) { // Each condition of a complete GPU-backed buffer range has its own reason. - const IndirectBufferView view = indirect_table_buffer(self, words, false, &reason, 16u << 20, true); + auto view = indirect_table_buffer(self, words, false, &reason, 16u << 20, true); + // Native scalar loads may name a small CPU window outside every placed buffer. + // Resolve GPU-backed ranges first; never replace their contents with a CPU snapshot. + if (reason && slot.scalar_window && words[0] != view_token_magic && + !std::strcmp(reason, "an input is in title memory outside any placed buffer")) { + const u64 address = words[0] | (u64{words[1] & 0xffff} << 32); + const UINT stride = (words[1] >> 16) & 0x3fff; + const u64 bytes = u64{stride ? stride : 1} * words[2]; + u64 start{}; + ID3D12Resource* chunk{}; + if (bytes >= slot.scalar_window && bytes <= 65536 && bytes % 4 == 0 && + readable_window(address, bytes) >= bytes && frame_copy(self, address, bytes, &start, &chunk) && chunk) { + view = {chunk, start, bytes, stride, true, 2}; + reason = nullptr; + } + } if (view.source == 1) InterlockedIncrement(&compute_inputs_gpu_copied); if (view.source == 2) { InterlockedIncrement(&compute_inputs_snapshot); From 808bc79a579f7cd1a7251d10eeacec5b493c9e2a Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Sat, 28 Nov 2026 10:59:10 +0000 Subject: [PATCH 44/44] tooling: allow the optional rectangle geometry shader in patch manifests The merged graphics loader reads .gs.cso for rectangle geometry, so .gs.cso is a valid but optional graphics translation file. Keep it out of the required set. --- tools/patch_manifest.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tools/patch_manifest.py b/tools/patch_manifest.py index b57bb465f2..b16abcbcc9 100644 --- a/tools/patch_manifest.py +++ b/tools/patch_manifest.py @@ -51,9 +51,10 @@ # mesh86_cache.inl; is the number each revision bump raises), the translation files the runtime reads for one # key, and the ones without which it has no translation. A later consumer must check which is current. compute # also needs .cs.hlsl when its .txt has no native line, and mesh86 reads .ps.cso only for a request with a pixel -# shader; this loader reads neither, so both stay optional. +# shader; this loader reads neither, so both stay optional. graphics reads .gs.cso only for a rectangle geometry +# program, so it is optional too. PIPELINES = { - "graphics": ("x2w-startup-shader-", (".txt", ".vs.cso", ".ps.cso"), (".txt", ".vs.cso", ".ps.cso")), + "graphics": ("x2w-startup-shader-", (".txt", ".vs.cso", ".ps.cso", ".gs.cso"), (".txt", ".vs.cso", ".ps.cso")), "compute": ("x2w-startup-shader-cs", (".txt", ".cs.cso", ".cs.hlsl"), (".txt", ".cs.cso")), "mesh86": ("x2w-startup-mesh-86-", (".mesh86.txt", ".ms.cso", ".ps.cso"), (".mesh86.txt", ".ms.cso")), }