diff --git a/docs/experiments.md b/docs/experiments.md index 13e4d28d40..546d3eb799 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -4806,6 +4806,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 new file mode 100644 index 0000000000..73e87d9eec --- /dev/null +++ b/docs/experiments/startup-gfx2hlsl-bvh-triangle.md @@ -0,0 +1,81 @@ +# `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}`. 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: + +- 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 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 binds `(size + 1) * 64` bytes. That binding 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`. These witnesses come from the CPU model (#2921), not a +hardware capture; the dispatch shows that the HLSL matches the model, not RDNA 2 hardware. It covers +all four kinds, each of the four ID map bytes, 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 unknown kinds 6 and 7 (instance and procedural in the model). + +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/checks/python-linux/startup_gfx2hlsl_bvh_triangle.txt b/tests/checks/python-linux/startup_gfx2hlsl_bvh_triangle.txt new file mode 100644 index 0000000000..ba93e995bf --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_bvh_triangle.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_bvh_triangle_check.py 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 9d04c1ef2d..5ca0ede59b 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 @@ -198,10 +198,22 @@ def dispatch_cases(): cases.append(dict(name=name, helper="x2w_bvh_intersect_box16", pointer=(offset >> 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), @@ -424,7 +446,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"), @@ -439,7 +460,7 @@ def controls(): ("node outside size", dict(node=0x25, word2=3), "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"), + ("size high bits", dict(word3=RESOURCE_TYPE | 0x100), "does not match node kind 5"), ] for label, kwargs, reason in cases: if label == "NSA address": @@ -487,7 +508,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,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 new file mode 100644 index 0000000000..792e61fcb5 --- /dev/null +++ b/tests/startup_gfx2hlsl_bvh_triangle_check.py @@ -0,0 +1,394 @@ +"""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) + 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)) + 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) + + # 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, "") + + # 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 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"), + ("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" + + +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 + 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 5142b5bb84..cf81493c4e 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -8120,18 +8120,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': @@ -8156,14 +8159,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: @@ -8174,8 +8177,14 @@ 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])) + # 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: raise Unsupported('%s absolute node base is not lowered' % name) @@ -8189,14 +8198,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])) @@ -11168,9 +11184,84 @@ 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. + # 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. 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 &&', + ' (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) > 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,',