From 1014e85f37416174e6523c2dffef2658c33f81a1 Mon Sep 17 00:00:00 2001 From: Leyukaka <45659323+Leyukaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:54:11 +0100 Subject: [PATCH] tooling: build slot 57 mesh profiles from runtime captures --- docs/experiments/native-fixed-mesh57.md | 8 ++ tests/native_direct_mesh_check.py | 56 ++++++++ tools/startup/mesh57_pixel_entry.py | 28 +--- tools/startup/mesh57_profile.py | 181 ++++++++++++++++++++++++ 4 files changed, 249 insertions(+), 24 deletions(-) create mode 100644 tools/startup/mesh57_profile.py diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index dcb0755f22..f0cff042f9 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -29,6 +29,14 @@ Set `X2W_SHADER_CACHE` to the request cache and `X2W_MESH57_CAPTURE_STATE=1` to Native preparation reads a separately reviewed `.mesh57-state` profile from the cache. The stand-in lists the cache's top-level file names once per process, at the first profile lookup (`src/startup_stubs/cache_index.h`), and opens a profile only when that listing has its name. A profile written while the process runs is read by the next process. Its versioned Windows x64 header is defined by `Mesh57Profile` in `src/startup_stubs/mesh57_profile.h`. The header supplies the MS entry layout and desktop fixed-function state. The file ends with the normalized descriptor, register blocks, serialized root and both guest programs. The stand-in compares every byte before building a PSO. The fixture authors this profile from its own known inputs. A captured register block alone does not establish the desktop rasterizer state or MS entry layout. +To serialize reviewed desktop and entry state, run +`python -B tools/startup/mesh57_profile.py ARCHIVE REVIEWED.json OUTPUT_DIR`. +Keep the three request companions beside the archive. The +`check_profile_writer` fixture in `tests/native_direct_mesh_check.py` shows a +complete version 2 record. The tool verifies capture keys and spans, then +atomically publishes `.mesh57-state` in the existing output directory, +replacing a same-named profile. Captures without a pixel shader are refused. + For the recognized 0x300-byte fixed layout, the variant key ignores relocation of the two shader record blocks and retains their relative offsets. `startup_indirect_mesh_create_result` checks two source-built relocated diff --git a/tests/native_direct_mesh_check.py b/tests/native_direct_mesh_check.py index bb788c092e..fef936e83d 100644 --- a/tests/native_direct_mesh_check.py +++ b/tests/native_direct_mesh_check.py @@ -1,4 +1,5 @@ """Source-built mesh ISA, direct DXIL validation and fail-closed controls.""" +import json from pathlib import Path import re import struct @@ -32,6 +33,55 @@ def assert_position_x(text, result_op): ), result_op +def check_profile_writer(folder, archive, profile, blob): + # Desktop state from the one-RTV native fixture in startup_indirect_draw_indexed.cpp. + state = { + "version": 2, + "mesh": dict(threads=64, vertices=3, primitives=1, topology=2, group_stride=64, wave_size=64), + "blend": dict(alpha_to_coverage=0, independent=0, targets=[ + dict(blend_enable=0, logic_op_enable=0, src=2, dest=1, op=1, + src_alpha=2, dest_alpha=1, op_alpha=1, logic_op=4, write_mask=15)]), + "rasterizer": dict(fill_mode=3, cull_mode=1, front_ccw=0, depth_bias=0, depth_bias_clamp=0, + slope_scaled_depth_bias=0, depth_clip=1, multisample=0, antialiased_line=0, + forced_sample_count=0, conservative_raster=0), + "depth_stencil": { + "depth_enable": 0, "depth_write_mask": 0, "depth_func": 8, "stencil_enable": 0, + "stencil_read_mask": 0, "stencil_write_mask": 0, + "front_face": {"fail": 0, "depth_fail": 0, "pass": 0, "func": 0}, + "back_face": {"fail": 0, "depth_fail": 0, "pass": 0, "func": 0}, + }, + "rt_formats": [28], + "depth_format": 0, + "samples": dict(count=1, quality=0, mask=0xffffffff), + "pixel": dict(enable=0, address=0, wave_size=64), + } + reviewed = folder / "reviewed.json" + output = folder / "authored" + output.mkdir() + tool = Path(__file__).resolve().parents[1] / "tools" / "startup" / "mesh57_profile.py" + + def run(record, error=None): + reviewed.write_text(json.dumps(record), encoding="utf-8") + result = subprocess.run([sys.executable, "-B", tool, archive, reviewed, output], capture_output=True, text=True) + if error: + assert result.returncode and error in result.stderr and not list(output.iterdir()), result + else: + assert result.returncode == 0, result.stderr + assert (output / profile.name).read_bytes() == blob + (output / profile.name).unlink() + + run(state) + run(dict(state, samples=dict(count=1, mask=0xffffffff)), "missing ['quality']") + run(dict(state, version=7), "expected profile version") + run(dict(state, version=1), "unexpected ['pixel']") + run(dict(state, version=3, constant=dict(sgpr=12, root_parameter=4, count=1)), + "creation root disagrees with profile version") + capture = archive.read_bytes() + archive.write_bytes(capture[:-1]) + run(state, "creation archive lengths disagree") + archive.write_bytes(capture) + + def checked_pixel_entry(folder, compiler, sdk): from mesh57_pixel_entry import pixel_entry from gfx2hlsl import fnv, mesh57_key @@ -61,8 +111,14 @@ def checked_pixel_entry(folder, compiler, sdk): parts = fixed + [root, ms, ps] header = bytearray(532) struct.pack_into("<8s6I", header, 0, b"X2WM572", *map(len, parts)) + struct.pack_into("<6I", header, 32, 64, 3, 1, 2, 64, 64) + struct.pack_into("<9IB", header, 64, 0, 0, 2, 1, 1, 2, 1, 1, 4, 15) + for offset, value in ((384, 3), (388, 1), (408, 1), (436, 8), (480, 28), (512, 1), + (520, 1), (528, 0xffffffff)): + struct.pack_into(" 0x1000 or len(data) != 20 + desc_size + a_size + b_size: - raise ValueError("creation archive key or lengths disagree") - desc = data[20:20 + desc_size] - a = data[20 + desc_size:20 + desc_size + a_size] - b = data[20 + desc_size + a_size:] - fields = struct.unpack_from("<15Q", desc) - if (any(fields[i] for i in (0,1,3,5,9,10,13)) or - (fields[2], fields[4], fields[6], fields[14]) != (len(a), len(b), len(ps), len(ms))): - raise ValueError("normalized mesh descriptor disagrees with request and state lengths") - variant = key - for part in (desc, a, b): - variant = fnv(part, fnv(struct.pack(" 0xffff or enable & ~address or wave not in (32, 64): raise ValueError("invalid reviewed pixel entry") - parts = (desc, a, b, root, ms, ps) if struct.unpack_from("<6I", data, 8) != tuple(map(len, parts)): raise ValueError("profile span lengths disagree") offset = header_size + 12 diff --git a/tools/startup/mesh57_profile.py b/tools/startup/mesh57_profile.py new file mode 100644 index 0000000000..34172fa13b --- /dev/null +++ b/tools/startup/mesh57_profile.py @@ -0,0 +1,181 @@ +"""Build a slot-57 profile from a capture and an explicitly reviewed JSON record. + +Use the field names in this script and numeric D3D12/DXGI values. The +check_profile_writer fixture in tests/native_direct_mesh_check.py shows a +complete example. List one blend record per RTV format. Unused RTV and +blend slots are zero-filled. Versions 2–6 require pixel, 3–6 constant, +4–6 views, and 5–6 heap_sgpr. +""" +import argparse +import json +import math +from pathlib import Path +import struct +import tempfile + +from gfx2hlsl import Unsupported, fnv, mesh57_key, parse_root + + +def read_creation(archive, request=None): + data = archive.read_bytes() + if len(data) < 20: + raise ValueError("truncated fixed creation archive") + key, desc_size, a_size, b_size = struct.unpack_from(" 0x1000 or len(data) != end_a + b_size: + raise ValueError("creation archive lengths disagree") + if request is None: + request = archive.with_name(f"req_{key:016x}.ps57") + ms, ps, root = (request.with_suffix(ext).read_bytes() for ext in (".m57", ".ps57", ".root")) + if request.name != f"req_{key:016x}.ps57" or mesh57_key(ms, ps, root) != key: + raise ValueError("raw MS, PS or creation root disagrees with request key") + desc, a, b = data[20:end_desc], data[end_desc:end_a], data[end_a:] + fields = struct.unpack_from("<15Q", desc) + if (any(fields[i] for i in (0, 1, 3, 5, 9, 10, 13)) or + (fields[2], fields[4], fields[6], fields[14]) != (len(a), len(b), len(ps), len(ms))): + raise ValueError("normalized mesh descriptor disagrees with request and state lengths") + variant = key + for part in (desc, a, b): + variant = fnv(part, fnv(struct.pack("= 3 and not heap_flags) or (version >= 5 and not heap_flags & 0x400)): + raise ValueError("creation root disagrees with profile version") + out = b"" + if version >= 2: + pixel = state["pixel"] + out += pack_record(pixel, "pixel", "3I", "enable address wave_size") + if pixel["address"] > 0xffff or pixel["enable"] & ~pixel["address"] or pixel["wave_size"] not in (32, 64): + raise ValueError("invalid reviewed pixel entry") + if version >= 3: + constant = state["constant"] + out += pack_record(constant, "constant", "3I", "sgpr root_parameter count") + if constant["root_parameter"] >= 16 or not 1 <= constant["count"] <= 8: + raise ValueError("invalid MS constant mapping") + if version >= 4: + views = state["views"] + if not isinstance(views, list) or not 1 <= len(views) <= 15: + raise ValueError("invalid MS view entry count") + out += struct.pack(" 1: + raise ValueError("invalid MS view mapping") + if version >= 5: + out += struct.pack(" 1 << 20 or len(ms) % 4 or len(ps) % 4: + raise ValueError("invalid creation root or shader lengths") + header = struct.pack("<8s6I", f"X2WM57{version}".encode("ascii"), *map(len, parts)) + fixed_state(state) + assert len(header) == 532 # Mesh57Profile in src/startup_stubs/mesh57_profile.h + return f"{variant:016x}.mesh57-state", header + extensions(state, version, root) + b"".join(parts) + + +def unique_fields(pairs): + record = {} + for name, value in pairs: + if name in record: + raise ValueError(f"duplicate reviewed field {name}") + record[name] = value + return record + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("archive", type=Path, help="req_.s57 beside its .m57, .ps57 and .root companions") + parser.add_argument("reviewed_state", type=Path, help="JSON record with explicitly reviewed desktop and entry fields") + parser.add_argument("output_dir", type=Path, help="existing directory to publish .mesh57-state") + args = parser.parse_args() + try: + state = json.loads(args.reviewed_state.read_text(encoding="utf-8"), object_pairs_hook=unique_fields) + name, profile = build_profile(args.archive, state) + output = args.output_dir / name + with tempfile.TemporaryDirectory(dir=args.output_dir) as staging: + staged = Path(staging) / name + staged.write_bytes(profile) + staged.replace(output) + except (OSError, ValueError, Unsupported, struct.error) as error: + parser.exit(1, f"{error}\n") + print(output) + + +if __name__ == "__main__": + main()