Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/experiments/native-fixed-mesh57.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<variant>.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 `<variant>.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
Expand Down
56 changes: 56 additions & 0 deletions tests/native_direct_mesh_check.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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("<I", header, offset, value)
profile = folder / f"{variant:016x}.mesh57-state"
blob = header + struct.pack("<3I", 0, 0, 64) + b"".join(parts)
check_profile_writer(folder, archive, profile, blob)
profile.write_bytes(blob)
layout = pixel_entry(request, archive, profile)
assert layout == "meshps1 0 0 64"
Expand Down
28 changes: 4 additions & 24 deletions tools/startup/mesh57_pixel_entry.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,13 @@
import struct
import sys

from gfx2hlsl import fnv, mesh57_key
from mesh57_profile import read_creation


def pixel_entry(request, archive, profile):
ms, ps, root = (request.with_suffix(ext).read_bytes() for ext in (".m57", ".ps57", ".root"))
key = mesh57_key(ms, ps, root)
if request.name != f"req_{key:016x}.ps57":
raise ValueError("raw MS, PS or creation root disagrees with request key")
data = archive.read_bytes()
if len(data) < 20:
raise ValueError("truncated fixed creation archive")
recorded, desc_size, a_size, b_size = struct.unpack_from("<Q3I", data)
if recorded != key or desc_size != 0x300 or max(a_size,b_size) > 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("<Q", len(part)), variant))
if archive.name != f"req_{variant:016x}.s57" or profile.name != f"{variant:016x}.mesh57-state":
raise ValueError("fixed-state variant disagrees with archive or profile name")
variant, parts = read_creation(archive, request)
if profile.name != f"{variant:016x}.mesh57-state":
raise ValueError("fixed-state variant disagrees with profile name")
data = profile.read_bytes()
# Mesh57Profile has a fixed Win32 ABI; the static assertion in mesh57_profile.h protects this offset.
header_size = 532
Expand All @@ -38,7 +19,6 @@ def pixel_entry(request, archive, profile):
enable, address, wave = struct.unpack_from("<3I", data, header_size)
if address > 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
Expand Down
181 changes: 181 additions & 0 deletions tools/startup/mesh57_profile.py
Original file line number Diff line number Diff line change
@@ -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("<Q3I", data)
end_desc = 20 + desc_size
end_a = end_desc + a_size
if desc_size != 0x300 or max(a_size, b_size) > 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("<Q", len(part)), variant))
if archive.name != f"req_{variant:016x}.s57":
raise ValueError("fixed-state variant disagrees with archive name")
return variant, (desc, a, b, root, ms, ps)


def require_fields(record, names, label):
required = set(names.split())
if not isinstance(record, dict):
raise ValueError(f"{label} must be an object")
missing, extra = required - record.keys(), record.keys() - required
if missing or extra:
raise ValueError(f"{label} fields disagree (missing {sorted(missing)}, unexpected {sorted(extra)})")


def pack_record(record, label, fmt, names):
require_fields(record, names, label)
values = [record[name] for name in names.split()]
if any(type(value) is float and not math.isfinite(value) for value in values):
raise ValueError(f"nonfinite value in {label}")
try:
return struct.pack("<" + fmt, *values)
except (struct.error, OverflowError) as error:
raise ValueError(f"invalid {label}: {error}") from error


def fixed_state(state):
mesh = state["mesh"]
entry = pack_record(mesh, "mesh", "6I", "threads vertices primitives topology group_stride wave_size")
if not (1 <= mesh["threads"] <= 128 and 1 <= mesh["vertices"] <= 256 and
1 <= mesh["primitives"] <= 256 and mesh["topology"] == 2 and mesh["wave_size"] in (32, 64)):
raise ValueError("unsupported mesh group, output dimensions, topology or wave size")
formats = state["rt_formats"]
if not isinstance(formats, list) or not 1 <= len(formats) <= 8:
raise ValueError("expected one to eight RTV formats")
blend = state["blend"]
require_fields(blend, "alpha_to_coverage independent targets", "blend")
targets = blend["targets"]
if not isinstance(targets, list) or len(targets) != len(formats):
raise ValueError("expected a blend target for each RTV format")
out = entry + struct.pack("<2I", blend["alpha_to_coverage"], blend["independent"])
for target in targets:
out += pack_record(target, "blend target", "9IB3x",
"blend_enable logic_op_enable src dest op src_alpha dest_alpha op_alpha logic_op write_mask")
out += bytes(40 * (8 - len(targets)))
out += pack_record(state["rasterizer"], "rasterizer", "3Ii2f5I",
"fill_mode cull_mode front_ccw depth_bias depth_bias_clamp slope_scaled_depth_bias "
"depth_clip multisample antialiased_line forced_sample_count conservative_raster")
depth = state["depth_stencil"]
fields = "depth_enable depth_write_mask depth_func stencil_enable stencil_read_mask stencil_write_mask"
require_fields(depth, fields + " front_face back_face", "depth_stencil")
out += pack_record({name: depth[name] for name in fields.split()}, "depth_stencil", "4I2B2x", fields)
for face in ("front_face", "back_face"):
out += pack_record(depth[face], face, "4I", "fail depth_fail pass func")
samples = state["samples"]
sample_bytes = pack_record(samples, "samples", "3I", "count quality mask")
if (((depth["depth_enable"] or depth["stencil_enable"]) and state["depth_format"] == 0) or
(samples["count"], samples["quality"], samples["mask"]) != (1, 0, 0xffffffff)):
raise ValueError("unsupported fixed attachment or sample state")
out += struct.pack("<10I", *formats, *([0] * (8 - len(formats))), len(formats), state["depth_format"])
return out + sample_bytes


def extensions(state, version, root):
signature = parse_root(root)
heap_flags = signature["flags"] & 0xc00
if ((version < 3 and (heap_flags or signature["params"])) or
(version >= 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("<I", len(views))
for view in views:
out += pack_record(view, "view", "3I", "sgpr root_parameter root_address")
if view["root_address"] > 1:
raise ValueError("invalid MS view mapping")
if version >= 5:
out += struct.pack("<I", state["heap_sgpr"])
return out


def build_profile(archive, state):
version = state.get("version") if isinstance(state, dict) else None
if type(version) is not int or not 1 <= version <= 6:
raise ValueError("expected profile version 1 through 6")
sections = "version mesh blend rasterizer depth_stencil rt_formats depth_format samples"
extra_sections = "pixel constant views heap_sgpr".split()[:version - 1]
require_fields(state, " ".join([sections, *extra_sections]), "profile")
variant, parts = read_creation(archive)
root, ms, ps = parts[3:]
if not ps:
raise ValueError("native slot 57 requires a pixel shader")
if not root or not ms or max(map(len, (root, ms, ps))) > 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_<variant>.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 <variant>.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()
Loading