From f1458a7916be7d2288a066ba72b0bab4ab40aae8 Mon Sep 17 00:00:00 2001 From: Roland Edi Date: Tue, 1 Dec 2026 10:54:12 +0000 Subject: [PATCH] tooling: draft reviewed slot 57 profiles from captures --- docs/experiments/native-fixed-mesh57.md | 33 +- .../python-linux/mesh57_profile_draft.txt | 1 + tests/cmake/mesh57_profile_draft.cmake | 13 + tests/mesh57_profile_draft_check.py | 435 ++++++++++++++++++ tools/startup/mesh57_profile.py | 394 +++++++++++++++- tools/startup/mesh57_profile_draft.py | 384 ++++++++++++++++ 6 files changed, 1239 insertions(+), 21 deletions(-) create mode 100644 tests/checks/python-linux/mesh57_profile_draft.txt create mode 100644 tests/cmake/mesh57_profile_draft.cmake create mode 100644 tests/mesh57_profile_draft_check.py create mode 100644 tools/startup/mesh57_profile_draft.py diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index c89904d521..c5f456dfc1 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -97,7 +97,38 @@ 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. +replacing a same-named profile. A record is refused while any required field +is null, while `review_required`, `provenance` or `capture` remains, or when a +reviewed value disagrees with a value the capture decoded. The refusal names +every field, not only the first. An empty `.ps57` is a depth-only profile: it +must have no RTV formats or blend targets, enabled depth writes and a typed +DSV format; versions 2–5 carry a zeroed pixel entry and version 6 is refused. + +To draft the review record instead of writing it by hand, run +`python -B tools/startup/mesh57_profile.py --draft ARCHIVE DRAFT.json`. +The draft decodes the mesh-layout depth-stencil words at `A+0x10C` and the +eight blend words at `A+0x124`, using the same rules as +`pipeline_state_decode.h`, `cb_blend.h` and `state_block_blend.h`. When the +adjacent `.t57` sidecar holds exactly one distinct attachment tuple, the draft +also fills `rt_formats`, `depth_format`, `samples.count` and `samples.quality`. +One line per tuple is +`targets dsv writable <0-or-1> samples `; +an `overflow ` line or more than one distinct tuple is refused. +Without a tuple those fields and `blend` stay null. The draft records the +capture's pixel export shape (`mrt0..mrt7`, `mrtz`, `null` or none) and the +attachment counts, and classifies a stage with a color export as `color`. +Mesh entry dimensions, rasterizer state, the pixel entry, root mappings and +the version remain reviewer-supplied: a register block alone does not assign +those offsets. `--check ARCHIVE REVIEWED.json` prints the complete unresolved +list and any capture disagreement without writing a profile. A review that +leaves attachments unverified (no `.t57`) is accepted only because a reviewer +supplied those values; the capture check then covers depth-stencil alone. +`--census DIRECTORY` prints the capture, stage, sidecar and consistency counts +without retaining shader or descriptor bytes. +The decoded depth-stencil and blend values are treated as measured facts: a +reviewed record that changes them is refused. A previously hand-authored +profile that chose a different canonical depth state therefore cannot be +recreated unchanged through this writer; keep the existing file instead. For the recognized 0x300-byte fixed layout, the variant key ignores relocation of the two shader record blocks and retains their relative offsets. diff --git a/tests/checks/python-linux/mesh57_profile_draft.txt b/tests/checks/python-linux/mesh57_profile_draft.txt new file mode 100644 index 0000000000..edf9935b9a --- /dev/null +++ b/tests/checks/python-linux/mesh57_profile_draft.txt @@ -0,0 +1 @@ +tests/mesh57_profile_draft_check.py diff --git a/tests/cmake/mesh57_profile_draft.cmake b/tests/cmake/mesh57_profile_draft.cmake new file mode 100644 index 0000000000..ed7c1fc155 --- /dev/null +++ b/tests/cmake/mesh57_profile_draft.cmake @@ -0,0 +1,13 @@ +# Source-built slot 57 profile authoring: depth-stencil and blend decoding, the .t57 +# attachment tuple, the color/depth stage classification, the reviewed-profile check +# that names every unresolved field, capture disagreement refusals, and an optional +# offline compile of the reviewed pixel entry. +if(TARGET compile_dxil AND EXISTS "${DXC_EXECUTABLE}") + add_test(NAME mesh57_profile_draft COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/mesh57_profile_draft_check.py" + "$" "${DXC_BIN_DIR}") +else() + add_test(NAME mesh57_profile_draft COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/mesh57_profile_draft_check.py") +endif() +set_tests_properties(mesh57_profile_draft PROPERTIES TIMEOUT 60) diff --git a/tests/mesh57_profile_draft_check.py b/tests/mesh57_profile_draft_check.py new file mode 100644 index 0000000000..80ddcc69bb --- /dev/null +++ b/tests/mesh57_profile_draft_check.py @@ -0,0 +1,435 @@ +"""Source-built controls for the slot 57 profile draft, review and refusal path. + +The captures are assembled here from the source-built mesh fixture, a four-word +pixel program and a serialized root from the existing checks. No title bytes, +game identifiers or GDK files are used. The optional arguments run the offline +pixel compiler on the reviewed entry; without them the pure-Python controls run +on their own. +""" +import json +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools" / "startup")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import mesh57_pixel_entry +import mesh57_profile +import mesh57_profile_draft +from gfx2hlsl import fnv, mesh57_key +from native_direct_mesh_check import triangle +from startup_gfx2hlsl_root_check import VALID_ROOT + + +TOOL = Path(__file__).resolve().parents[1] / "tools" / "startup" / "mesh57_profile.py" +MS = struct.pack("<%dI" % len(triangle()), *triangle()) +COLOR_PS = struct.pack("<4I", 0x7E0002F2, 0xF800180F, 0, 0xBF810000) +MRT1_PS = struct.pack("<4I", 0x7E0002F2, 0xF800181F, 0, 0xBF810000) +DEPTH_PS = struct.pack("<3I", 0xF8001881, 0, 0xBF810000) +NULL_PS = struct.pack("<6I", 0xC8020002, 0x7C0800F0, 0x8AFE6A7E, 0xF8001890, 0, 0xBF810000) +DISABLED_BLEND = (0x80000000,) * 8 +TWO_TARGETS = "targets 2 29 28 dsv 45 writable 1 samples 4 3\n" + + +def block_a(depth=0x16, stencil=0, front=0, back=0, *, tag=6, blend=DISABLED_BLEND): + block = bytearray(b"\x5a" * 0x1D8) + struct.pack_into(" 532 and header[:8] == b"X2WM572\0" + assert struct.unpack_from("<6I", header, 8) == tuple(map(len, ( + bytes(0x300), block_a(blend=words), b"state-b", VALID_ROOT, MS, COLOR_PS))) + assert struct.unpack_from("<6I", header, 32) == (64, 3, 1, 2, 64, 64) + assert struct.unpack_from("<2I", header, 56) == (0, 1) + assert struct.unpack_from("<9IB3x", header, 64) == (1, 0, 5, 6, 1, 2, 6, 1, 4, 15) + assert struct.unpack_from("<9IB3x", header, 104) == (1, 0, 3, 2, 1, 5, 2, 1, 4, 15) + assert struct.unpack_from("<3I", header, 512) == (2, 45, 1) + assert struct.unpack_from("<3I", header, 520) == (1, 0, 0xFFFFFFFF) + assert struct.unpack_from("<3I", blob, 532) == (0, 0, 64) + + output = folder / "profiles" + output.mkdir() + result = run(TOOL, archive, reviewed, output) + assert result.returncode == 0, result.stderr + written = output / name + assert written.read_bytes() == blob + assert len(written.read_bytes()) > 532 + assert mesh57_pixel_entry.pixel_entry(request, archive, written) == "meshps1 0 0 64" + + if compiler is not None and dxc is not None: + request.with_suffix(".pslayout").write_text("meshps1 0 0 64\n", encoding="ascii") + (folder / "cache").mkdir() + dxil = folder / "reviewed.dxil" + result = subprocess.run([str(compiler), str(dxc), str(folder / "cache"), "gfx1013-raw-mesh-ps", + str(request), str(dxil)], capture_output=True, text=True) + assert result.returncode == 0, result.stdout + result.stderr + assert dxil.read_bytes()[:4] == b"DXBC" + + +def check_mismatches(folder): + archive, _ = capture(folder, state_a=block_a(blend=(0xE5010504, *DISABLED_BLEND[1:])), + t57="targets 1 28 dsv 45 writable 1 samples 1 0\n") + draft = mesh57_profile_draft.build_draft(archive) + state = complete_review(draft, version=2) + reviewed = folder / "reviewed.json" + + def expect(edit, text): + edited = json.loads(json.dumps(state)) + edit(edited) + reviewed.write_text(json.dumps(edited), encoding="utf-8") + result = run(TOOL, "--check", archive, reviewed) + texts = (text,) if isinstance(text, str) else text + assert result.returncode and all(item in result.stdout for item in texts), (text, result.stdout) + output = folder / "out" + output.mkdir(exist_ok=True) + result = run(TOOL, archive, reviewed, output) + assert result.returncode and not list(output.iterdir()), (text, result.stderr) + + expect(lambda value: value["depth_stencil"].update(depth_func=7), "depth_stencil.depth_func") + expect(lambda value: value["blend"]["targets"][0].update(src=2), "blend.targets[0].src") + expect(lambda value: value.update(rt_formats=[29]), "rt_formats[0]") + expect(lambda value: value.update(depth_format=40, samples= {"count": 4, "quality": 3, "mask": 0xFFFFFFFF}), + ("depth_format", "samples.count", "samples.quality")) + expect(lambda value: value["samples"].update(mask=None), "profile.samples.mask is null") + expect(lambda value: value.update(review_required=False), "review_required marker still present") + expect(lambda value: value.update(unexpected=1), "profile has unexpected field unexpected") + + +def check_sidecar_refusals(folder): + archive, _ = capture(folder, state_a=block_a(blend=(0xE5010504, *DISABLED_BLEND[1:]))) + sidecar = archive.with_suffix(".t57") + first = "targets 1 28 dsv 45 writable 1 samples 1 0\n" + second = "targets 1 29 dsv 45 writable 1 samples 1 0\n" + sidecar.write_text(first + second, encoding="utf-8") + refused(mesh57_profile_draft.build_draft, "conflicting attachment observations", archive) + sidecar.write_text(first + "overflow 2\n", encoding="utf-8") + refused(mesh57_profile_draft.build_draft, "overflow 2", archive) + sidecar.write_text("targets 1 28 dsv 45 writable 1 samples\n", encoding="utf-8") + refused(mesh57_profile_draft.build_draft, "invalid attachment tuple", archive) + sidecar.write_text("targets 1 0 dsv 45 writable 1 samples 1 0\n", encoding="utf-8") + refused(mesh57_profile_draft.build_draft, "invalid attachment values", archive) + sidecar.write_text(first + first, encoding="utf-8") + assert mesh57_profile_draft.build_draft(archive)["rt_formats"] == [28] + sidecar.write_text("", encoding="utf-8") + draft = mesh57_profile_draft.build_draft(archive) + assert draft["rt_formats"] is None and draft["depth_format"] is None and draft["blend"] is None + assert draft["capture"]["sidecar"] is True and draft["capture"]["rtv_count"] is None + + color, _ = capture(folder / "color", ps=COLOR_PS) + color.with_suffix(".t57").write_text("targets 0 dsv 45 writable 1 samples 1 0\n", encoding="utf-8") + refused(mesh57_profile_draft.build_draft, "pixel shader exports mrtN", color) + + empty, _ = capture(folder / "empty", ps=b"") + empty.with_suffix(".t57").write_text(first, encoding="utf-8") + refused(mesh57_profile_draft.build_draft, "empty .ps57", empty) + + mrt1, _ = capture(folder / "mrt1", ps=MRT1_PS) + mrt1.with_suffix(".t57").write_text(first, encoding="utf-8") + refused(mesh57_profile_draft.build_draft, "exports mrt1", mrt1) + + depth, _ = capture(folder / "depth", ps=DEPTH_PS) + depth.with_suffix(".t57").write_text("targets 0 dsv 0 writable 0 samples 1 0\n", encoding="utf-8") + refused(mesh57_profile_draft.build_draft, "exports depth but", depth) + + readonly, _ = capture(folder / "readonly", state_a=block_a()) + readonly.with_suffix(".t57").write_text("targets 1 28 dsv 45 writable 0 samples 1 0\n", encoding="utf-8") + refused(mesh57_profile_draft.build_draft, "DSV is not writable", readonly) + + +def check_depth_only(folder): + archive, _ = capture(folder / "capture", ps=b"", state_a=block_a(0x66), + t57="targets 0 dsv 55 writable 1 samples 1 0\n") + draft = mesh57_profile_draft.build_draft(archive) + assert draft["capture"]["pixel_stage"] == "empty" + assert draft["rt_formats"] == [] and draft["depth_format"] == 55 + assert draft["blend"] == dict(alpha_to_coverage=None, independent=False, targets=[]) + + state = complete_review(draft, version=1) + assert mesh57_profile_draft.review_issues(archive, state) == [] + name, blob = mesh57_profile.build_profile(archive, state) + header = blob[:532] + assert header[:8] == b"X2WM571\0" + assert struct.unpack_from("<2I", header, 512) == (0, 55) + assert struct.unpack_from("<3I", header, 520) == (1, 0, 0xFFFFFFFF) + # The fixed disabled RT0 entry keeps the blend structure canonical. + assert struct.unpack_from("<9IB3x", header, 64) == (0, 0, 2, 1, 1, 2, 1, 1, 4, 15) + + zero_pixel = complete_review(draft, version=2, pixel=(0, 0, 0)) + name, blob = mesh57_profile.build_profile(archive, zero_pixel) + assert blob[:8] == b"X2WM572\0" + assert struct.unpack_from("<3I", blob, 532) == (0, 0, 0) + nonzero_pixel = complete_review(draft, version=2, pixel=(0, 0, 64)) + refused(mesh57_profile.build_profile, "depth-only profile contains pixel entry metadata", + archive, nonzero_pixel) + + write_off, _ = capture(folder / "write-off", ps=b"", state_a=block_a(0x12)) + write_off_draft = mesh57_profile_draft.build_draft(write_off) + write_off_draft.update(rt_formats=[], depth_format=55, + blend=dict(alpha_to_coverage=None, independent=0, targets=[]), + samples=dict(count=1, quality=0, mask=0xFFFFFFFF)) + write_off_state = complete_review(write_off_draft, version=1) + refused(mesh57_profile.build_profile, "depth-only profile requires enabled depth writes", + write_off, write_off_state) + + untyped, _ = capture(folder / "untyped", ps=b"", state_a=block_a(0x66)) + untyped_draft = mesh57_profile_draft.build_draft(untyped) + untyped_draft.update(rt_formats=[], depth_format=28, + blend=dict(alpha_to_coverage=None, independent=0, targets=[]), + samples=dict(count=1, quality=0, mask=0xFFFFFFFF)) + untyped_state = complete_review(untyped_draft, version=1) + refused(mesh57_profile.build_profile, "depth-only profile requires a typed DSV format", + untyped, untyped_state) + + version6 = complete_review(draft, version=6, pixel=(0, 0, 0)) + version6.update(constant=dict(sgpr=12, root_parameter=4, count=1), + views=[dict(sgpr=16, root_parameter=0, root_address=0)], heap_sgpr=19) + refused(mesh57_profile.build_profile, "depth-only profile cannot use pixel heap version 6", + archive, version6) + + +def check_census(folder): + folder.mkdir(parents=True, exist_ok=True) + good, _ = capture(folder, state_a=block_a()) + good.with_suffix(".t57").write_text("targets 1 28 dsv 45 writable 1 samples 1 0\n", encoding="utf-8") + empty, _ = capture(folder, ps=b"", state_a=block_a(0x66)) + empty.with_suffix(".t57").write_text("targets 0 dsv 55 writable 1 samples 1 0\n", encoding="utf-8") + bad, _ = capture(folder, ps=MRT1_PS) + bad.with_suffix(".t57").write_text("targets 1 28 dsv 45 writable 1 samples 1 0\n", encoding="utf-8") + (folder / "req_0000000000000001.s57").write_bytes(b"bad!") + + result = run(TOOL, "--census", folder) + assert result.returncode == 0, result.stderr + assert "captures 4: color 2, depth 0, null 0, param 0, none 0, empty 1, refused 1" in result.stdout, result.stdout + assert "sidecars 3, attachment tuples 3, consistent stage/attachment pairs 2" in result.stdout, result.stdout + result = run(TOOL, "--census", folder, "--verbose") + assert result.returncode == 0, result.stderr + lines = [line for line in result.stdout.splitlines() if line.startswith("req_")] + assert len(lines) == 4 and any("refused" in line for line in lines), result.stdout + + +def main(): + compiler = Path(sys.argv[1]) if len(sys.argv) > 1 else None + dxc = Path(sys.argv[2]) if len(sys.argv) > 2 else None + check_classification() + check_depth_decode() + check_blend_words() + with tempfile.TemporaryDirectory(prefix="mesh57-profile-") as temporary: + root = Path(temporary) + check_color_draft(root / "draft") + check_color_review(root / "review", compiler, dxc) + check_mismatches(root / "mismatch") + check_sidecar_refusals(root / "sidecar") + check_depth_only(root / "depth") + check_census(root / "census") + print("slot 57 profile draft, review, depth-only and refusal checks passed") + + +if __name__ == "__main__": + main() diff --git a/tools/startup/mesh57_profile.py b/tools/startup/mesh57_profile.py index 34172fa13b..cdb4d17f4f 100644 --- a/tools/startup/mesh57_profile.py +++ b/tools/startup/mesh57_profile.py @@ -1,21 +1,65 @@ -"""Build a slot-57 profile from a capture and an explicitly reviewed JSON record. +"""Draft or build a slot-57 profile from a fixed creation capture. 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. +4–6 views, and 5–6 heap_sgpr. An empty .ps57 is a depth-only profile: it +has no RTV formats or blend targets, needs enabled depth writes and a typed +DSV format, and versions 2–5 carry a zeroed pixel record. + +``--draft ARCHIVE DRAFT_JSON`` writes a draft with the depth-stencil and +blend fields decoded from state block A and the attachments read from the +adjacent .t57 sidecar when it exists. Fields the capture does not locate +stay null. ``--check ARCHIVE REVIEWED_JSON`` lists every field that still +needs review and every field whose reviewed value disagrees with the +capture, without writing a profile. """ import argparse import json import math from pathlib import Path +import re import struct +import sys import tempfile +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import disasm_rdna2 as disasm + from gfx2hlsl import Unsupported, fnv, mesh57_key, parse_root +PROFILE_PREFIX = struct.Struct("<8s6I") +RASTERIZER_OFFSET = 384 # From the start of Mesh57Profile. + +# DXGI_FORMAT_D32_FLOAT_S8X24_UINT, D32_FLOAT, D24_UNORM_S8_UINT, D16_UNORM. +TYPED_DSV_FORMATS = (20, 40, 45, 55) + +MESH_FIELDS = "threads vertices primitives topology group_stride wave_size" +RASTERIZER_FIELDS = ("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") +BLEND_TARGET_FIELDS = ("blend_enable logic_op_enable src dest op src_alpha dest_alpha op_alpha logic_op " + "write_mask") +PIXEL_FIELDS = "enable address wave_size" +CONSTANT_FIELDS = "sgpr root_parameter count" + +MESH_LAYOUT_OFFSET = 0x004 +MESH_LAYOUT_TAG = 6 +MESH_DEPTH_OFFSET = 0x10C +DEPTH_WORDS = struct.Struct("<4I") +MESH_BLEND_OFFSET = 0x124 +BLEND_WORDS = struct.Struct("<8I") + +# D3D12_BLEND by guest BlendOp, without the optional alpha blend factor feature. +BLEND_FACTORS = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 0, 14, 15, 16, 17, 18, 19) +ALPHA_FORMS = {3: 5, 4: 6, 9: 7, 10: 8, 16: 18, 17: 19} +# D3D12_BLEND_OP for guest ADD, SUBTRACT, MIN, MAX and REVERSE_SUBTRACT. +BLEND_OPS = (1, 2, 4, 5, 3) +TARGET_TUPLE = re.compile( + r"targets ([0-8])((?: [0-9]+){0,8}) dsv ([0-9]+) writable ([01]) samples ([0-9]+) ([0-9]+)") + + def read_creation(archive, request=None): data = archive.read_bytes() if len(data) < 20: @@ -43,6 +87,288 @@ def read_creation(archive, request=None): return variant, (desc, a, b, root, ms, ps) +def validate_stage_lengths(root, ms, ps): + 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") + + +def has_mesh_layout(block): + return (len(block) >= MESH_LAYOUT_OFFSET + 4 and + struct.unpack_from("> lo) & ((1 << (hi - lo + 1)) - 1) + + +def stencil_op(op, opval): + # Guest encodings mapped to D3D12 KEEP, ZERO, REPLACE, INCR_SAT, DECR_SAT, + # INVERT, INCR and DECR. Add and subtract can only use a step of one. + desktop_ops = {0: 1, 1: 2, 3: 3, 5: 4, 6: 5, 7: 6, 8: 7, 9: 8} + if op in desktop_ops and (op not in (5, 6, 8, 9) or opval == 1): + return desktop_ops[op] + raise ValueError("stencil op without a D3D12 form (ONES, REPLACE_OP, logic op, or add / subtract by other than one)") + + +def stencil_face(control, lo, compare, opval): + return { + "fail": stencil_op(bits(control, lo, lo + 3), opval), + "pass": stencil_op(bits(control, lo + 4, lo + 7), opval), + "depth_fail": stencil_op(bits(control, lo + 8, lo + 11), opval), + "func": compare + 1, + } + + +def decode_mesh_depth_stencil(block): + """Decode the mesh-layout words with the rules of pipeline_state_decode.h.""" + if len(block) < MESH_LAYOUT_OFFSET + 4: + raise ValueError("state block A too short for the mesh layout tag") + if not has_mesh_layout(block): + raise ValueError("draft requires mesh layout tag 6 in state block A") + if len(block) < MESH_DEPTH_OFFSET + DEPTH_WORDS.size: + raise ValueError("state block A too short for the mesh depth-stencil words") + depth, stencil, refmask, refmask_bf = DEPTH_WORDS.unpack_from(block, MESH_DEPTH_OFFSET) + if bits(depth, 30, 31): + raise ValueError("colour writes tied to the depth result (DB_DEPTH_CONTROL bits 30-31)") + + depth_enable = bits(depth, 1, 1) + stencil_enable = bits(depth, 0, 0) + stencil_ref = None + if stencil_enable: + front = stencil_face(stencil, 0, bits(depth, 8, 10), bits(refmask, 24, 31)) + back = front.copy() + if bits(depth, 7, 7): + back = stencil_face(stencil, 12, bits(depth, 20, 22), bits(refmask_bf, 24, 31)) + if bits(refmask_bf, 0, 23) != bits(refmask, 0, 23): + raise ValueError("front and back stencil masks or reference differ") + read_mask = bits(refmask, 8, 15) + write_mask = bits(refmask, 16, 23) + stencil_ref = bits(refmask, 0, 7) + else: + read_mask = write_mask = 0xFF + front = {"fail": 1, "depth_fail": 1, "pass": 1, "func": 8} + back = front.copy() + if bits(depth, 3, 3): + raise ValueError("depth bounds enabled (DB_DEPTH_CONTROL bit 3)") + return { + "depth_enable": depth_enable, + "depth_write_mask": depth_enable & bits(depth, 2, 2), + "depth_func": bits(depth, 4, 6) + 1 if depth_enable else 8, + "stencil_enable": stencil_enable, + "stencil_read_mask": read_mask, + "stencil_write_mask": write_mask, + "front_face": front, + "back_face": back, + }, stencil_ref + + +def blend_factor(op, *, alpha=False): + if op in (19, 20): + if alpha: + # CONSTANT_ALPHA reads the blend constant's alpha in these slots. + return 14 if op == 19 else 15 # BLEND_FACTOR / INV_BLEND_FACTOR + raise ValueError("CONSTANT_ALPHA factor without alpha blend factor support") + if op in (11, 12): + raise ValueError("BOTH_SRC_ALPHA / BOTH_INV_SRC_ALPHA factor") + if op >= len(BLEND_FACTORS): + raise ValueError("unknown blend factor") + return BLEND_FACTORS[op] + + +def decode_blend_word(word): + """Mirror cb_blend.h and the slot 57 caller's alpha_factor_supported=false.""" + if not bits(word, 30, 30): + return dict(blend_enable=False, src=2, dest=1, op=1, src_alpha=2, dest_alpha=1, op_alpha=1) + + color_src, color_op, color_dest = bits(word, 0, 4), bits(word, 5, 7), bits(word, 8, 12) + if bits(word, 29, 29): + alpha_src, alpha_op, alpha_dest = bits(word, 16, 20), bits(word, 21, 23), bits(word, 24, 28) + else: + alpha_src, alpha_op, alpha_dest = color_src, color_op, color_dest + + src, dest = blend_factor(color_src), blend_factor(color_dest) + src_alpha, dest_alpha = blend_factor(alpha_src, alpha=True), blend_factor(alpha_dest, alpha=True) + if max(color_op, alpha_op) >= len(BLEND_OPS): + raise ValueError("unknown combine function") + op, op_alpha = BLEND_OPS[color_op], BLEND_OPS[alpha_op] + if ((op in (4, 5) and (src, dest) != (2, 2)) or + (op_alpha in (4, 5) and (src_alpha, dest_alpha) != (2, 2))): + raise ValueError("MIN / MAX with factors other than ONE") + return dict(blend_enable=True, src=src, dest=dest, op=op, + src_alpha=ALPHA_FORMS.get(src_alpha, src_alpha), + dest_alpha=ALPHA_FORMS.get(dest_alpha, dest_alpha), op_alpha=op_alpha) + + +def decode_mesh_blend(block): + """Decode all eight CB_BLENDn_CONTROL words; the caller already checked layout tag 6.""" + if len(block) < MESH_BLEND_OFFSET + BLEND_WORDS.size: + raise ValueError("state block A too short for the mesh blend words") + targets = [] + target0_dual_source = False + for index, word in enumerate(BLEND_WORDS.unpack_from(block, MESH_BLEND_OFFSET)): + try: + target = decode_blend_word(word) + dual_source = any(target[field] in (16, 17, 18, 19) + for field in ("src", "dest", "src_alpha", "dest_alpha")) + if index == 0: + target0_dual_source = dual_source + elif target["blend_enable"]: + if dual_source: + raise ValueError("dual-source factor on a target other than 0") + if target0_dual_source: + raise ValueError("dual-source blend on target 0 with another blending target") + except ValueError as error: + raise ValueError(f"CB_BLEND{index}_CONTROL 0x{word:08x}: {error}") from error + targets.append(target) + return targets + + +def read_targets(sidecar): + """One distinct .t57 attachment tuple, or None when the file or a tuple is absent.""" + try: + lines = sidecar.read_text(encoding="utf-8").splitlines() + except FileNotFoundError: + return None + + observations = {} + overflow = None + for number, line in enumerate(lines, 1): + if not line.strip(): + continue + marker = re.fullmatch(r"overflow ([1-9][0-9]*)", line) + if marker and overflow is None: + overflow = marker[1] + continue + match = TARGET_TUPLE.fullmatch(line) + if not match or overflow is not None: + raise ValueError(f"invalid attachment tuple or overflow marker in {sidecar.name} line {number}") + rtvs = tuple(map(int, match[2].split())) + dsv, writable, count, quality = map(int, match.group(3, 4, 5, 6)) + if (len(rtvs) != int(match[1]) or 0 in rtvs or not count or + (not dsv and writable) or max((*rtvs, dsv, count, quality)) > 0xFFFFFFFF): + raise ValueError(f"invalid attachment values in {sidecar.name} line {number}") + observations[rtvs, dsv, writable, count, quality] = line + + if len(observations) > 1 or overflow is not None: + details = list(observations.values()) + if overflow is not None: + details.append(f"overflow {overflow}") + raise ValueError(f"conflicting attachment observations in {sidecar.name}: " + "; ".join(details)) + return next(iter(observations), None) + + +def read_captured_state(sidecar, block_a, ps, *, require_mesh_layout=False): + captured = {} + stencil_ref = None + mesh_layout = has_mesh_layout(block_a) + if mesh_layout or require_mesh_layout: + captured["depth_stencil"], stencil_ref = decode_mesh_depth_stencil(block_a) + observations = read_targets(sidecar) + if observations is not None: + rtvs, dsv, _, count, quality = observations + captured.update(rt_formats=list(rtvs), depth_format=dsv, samples=dict(count=count, quality=quality)) + if mesh_layout: + targets = decode_mesh_blend(block_a)[:len(rtvs) if ps else 0] + captured["blend"] = dict(independent=any(target != targets[0] for target in targets[1:]), + targets=targets) + return captured, stencil_ref, observations + + +def classify_pixel(ps): + """Name the exports a raw pixel program reaches; no title bytes are retained.""" + if not ps: + return dict(kind="empty", color_targets=[], depth_export=False, null_exports=0, param_exports=[]) + try: + instructions = disasm.disassemble_binary(ps, "slot57-ps") + except Exception as error: # disasm has no single exception type for a malformed stream + raise ValueError(f"pixel shader disassembly failed: {error}") from error + targets = [] + for instruction in instructions: + if instruction.get("opcode") != "exp": + continue + assembly = instruction.get("assembly", "") + fields = assembly.split() + if len(fields) < 2 or fields[0] != "exp": + raise ValueError(f"unrecognized pixel export at byte {instruction.get('offset')}") + targets.append(fields[1]) + color = sorted({int(target[3:]) for target in targets if re.fullmatch(r"mrt[0-7]", target)}) + params = sorted({int(target[5:]) for target in targets if re.fullmatch(r"param[0-9]+", target)}) + depth_export = "mrtz" in targets + null_exports = targets.count("null") + if color: + kind = "color" + elif depth_export: + kind = "depth" + elif params: + kind = "param" + elif null_exports: + kind = "null" + else: + kind = "none" + return dict(kind=kind, color_targets=color, depth_export=depth_export, + null_exports=null_exports, param_exports=params) + + +def stage_consistency(stage, depth_stencil, observations, ps): + """Refuse a stage/attachment pair that cannot describe the same pipeline.""" + if observations is None: + return [] + rtvs, dsv, writable, _, _ = observations + count = len(rtvs) + issues = [] + if stage["kind"] == "empty" and count: + issues.append(f"empty .ps57 but the .t57 tuple has {count} target(s)") + elif stage["kind"] == "color": + if not count: + issues.append("pixel shader exports mrtN but the .t57 tuple has no targets") + elif max(stage["color_targets"]) >= count: + issues.append(f"pixel shader exports mrt{max(stage['color_targets'])} but the tuple has {count} target(s)") + elif stage["kind"] in ("null", "none", "param") and count: + issues.append(f"pixel shader has no color export but the tuple has {count} target(s)") + if dsv == 0 and depth_stencil["depth_enable"]: + issues.append("depth is enabled but the .t57 tuple has no DSV") + if dsv == 0 and stage["depth_export"]: + issues.append("pixel shader exports depth but the .t57 tuple has no DSV") + if dsv and depth_stencil["depth_write_mask"] and not writable: + issues.append("depth writes are enabled but the .t57 tuple's DSV is not writable") + if count == 0 and dsv == 0: + issues.append("the .t57 tuple has neither a color target nor a DSV") + if not ps: + if not depth_stencil["depth_enable"] or depth_stencil["depth_write_mask"] != 1: + issues.append("empty .ps57 requires enabled depth writes") + if dsv not in TYPED_DSV_FORMATS: + issues.append("empty .ps57 requires a typed DSV format") + return issues + + +def capture_mismatches(captured, reviewed, path): + if isinstance(captured, dict) and isinstance(reviewed, dict): + for name, value in captured.items(): + yield from capture_mismatches(value, reviewed.get(name), f"{path}.{name}") + elif isinstance(captured, list) and isinstance(reviewed, list) and len(captured) == len(reviewed): + for index, (expected, actual) in enumerate(zip(captured, reviewed)): + yield from capture_mismatches(expected, actual, f"{path}[{index}]") + elif captured != reviewed: + yield path + + +def null_paths(value, path): + if value is None: + yield path + elif isinstance(value, dict): + for name, field in value.items(): + yield from null_paths(field, f"{path}.{name}") + elif isinstance(value, list): + for index, field in enumerate(value): + yield from null_paths(field, f"{path}[{index}]") + + +def require_reviewed_values(value, path): + missing = list(null_paths(value, path)) + if missing: + raise ValueError(f"profile is incomplete: {len(missing)} unreviewed field(s): " + ", ".join(missing)) + + def require_fields(record, names, label): required = set(names.split()) if not isinstance(record, dict): @@ -63,15 +389,17 @@ def pack_record(record, label, fmt, names): raise ValueError(f"invalid {label}: {error}") from error -def fixed_state(state): +def fixed_state(state, depth_only=False): mesh = state["mesh"] - entry = pack_record(mesh, "mesh", "6I", "threads vertices primitives topology group_stride wave_size") + entry = pack_record(mesh, "mesh", "6I", MESH_FIELDS) 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: + if not isinstance(formats, list) or (not depth_only and not 1 <= len(formats) <= 8): raise ValueError("expected one to eight RTV formats") + if depth_only and len(formats) != 0: + raise ValueError("depth-only profile has color targets") blend = state["blend"] require_fields(blend, "alpha_to_coverage independent targets", "blend") targets = blend["targets"] @@ -79,16 +407,22 @@ def fixed_state(state): 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(target, "blend target", "9IB3x", BLEND_TARGET_FIELDS) + if depth_only: + # Match the native depth fixture's disabled blend state (ONE/ZERO, ADD, NOOP, all channels). + out += struct.pack("<9IB3x", 0, 0, 2, 1, 1, 2, 1, 1, 4, 15) + out += bytes(RASTERIZER_OFFSET - PROFILE_PREFIX.size - len(out)) 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") + RASTERIZER_FIELDS) 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) + if depth_only: + if not depth["depth_enable"] or depth["depth_write_mask"] != 1: + raise ValueError("depth-only profile requires enabled depth writes") + if state["depth_format"] not in TYPED_DSV_FORMATS: + raise ValueError("depth-only profile requires a typed DSV format") for face in ("front_face", "back_face"): out += pack_record(depth[face], face, "4I", "fail depth_fail pass func") samples = state["samples"] @@ -100,7 +434,9 @@ def fixed_state(state): return out + sample_bytes -def extensions(state, version, root): +def extensions(state, version, root, depth_only=False): + if depth_only and version == 6: + raise ValueError("depth-only profile cannot use pixel heap version 6") signature = parse_root(root) heap_flags = signature["flags"] & 0xc00 if ((version < 3 and (heap_flags or signature["params"])) or @@ -109,12 +445,15 @@ def extensions(state, version, root): 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): + out += pack_record(pixel, "pixel", "3I", PIXEL_FIELDS) + if depth_only: + if any(pixel.values()): + raise ValueError("depth-only profile contains pixel entry metadata") + elif 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") + out += pack_record(constant, "constant", "3I", CONSTANT_FIELDS) if constant["root_parameter"] >= 16 or not 1 <= constant["count"] <= 8: raise ValueError("invalid MS constant mapping") if version >= 4: @@ -132,6 +471,9 @@ def extensions(state, version, root): def build_profile(archive, state): + if isinstance(state, dict) and "review_required" in state: + raise ValueError("profile is incomplete: review_required marker must be removed after review") + require_reviewed_values(state, "profile") 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") @@ -140,13 +482,22 @@ def build_profile(archive, state): 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) + validate_stage_lengths(root, ms, ps) + captured, _, observations = read_captured_state(archive.with_suffix(".t57"), parts[1], ps) + if "depth_stencil" in captured: + inconsistent = stage_consistency(classify_pixel(ps), captured["depth_stencil"], observations, ps) + if inconsistent: + raise ValueError("capture is inconsistent: " + "; ".join(inconsistent)) + mismatches = [path for section, value in captured.items() + for path in capture_mismatches(value, state[section], section)] + if mismatches: + raise ValueError("reviewed state disagrees with capture: " + ", ".join(mismatches)) + depth_only = not ps + header = PROFILE_PREFIX.pack(f"X2WM57{version}".encode("ascii"), *map(len, parts)) + header += fixed_state(state, depth_only) 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) + return (f"{variant:016x}.mesh57-state", + header + extensions(state, version, root, depth_only) + b"".join(parts)) def unique_fields(pairs): @@ -159,6 +510,9 @@ def unique_fields(pairs): def main(): + if len(sys.argv) > 1 and sys.argv[1] in ("--draft", "--check", "--census"): + from mesh57_profile_draft import draft_main + raise SystemExit(draft_main(sys.argv[1:])) 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") diff --git a/tools/startup/mesh57_profile_draft.py b/tools/startup/mesh57_profile_draft.py new file mode 100644 index 0000000000..39959fafce --- /dev/null +++ b/tools/startup/mesh57_profile_draft.py @@ -0,0 +1,384 @@ +"""Draft a slot-57 review record from a fixed creation capture. + +The capture and its adjacent .t57 sidecar hold the measured state block A, +the attachments and the two shaders. This tool decodes only the fields whose +register meanings are established (depth-stencil, blend, RTV/DSV formats and +samples), records where each value came from, and leaves every other field +null for a reviewer. It never copies SHA/bytecode into the review record. + +``mesh57_profile.py --check`` lists every unresolved field and every +reviewed value that disagrees with the capture. A profile is written only +after those lists are empty. +""" +import argparse +import json +from pathlib import Path +import struct +import sys + +from mesh57_profile import ( + BLEND_TARGET_FIELDS, + CONSTANT_FIELDS, + MESH_BLEND_OFFSET, + MESH_FIELDS, + PIXEL_FIELDS, + RASTERIZER_FIELDS, + Unsupported, + build_profile, + capture_mismatches, + classify_pixel, + read_captured_state, + read_creation, + stage_consistency, + validate_stage_lengths, +) + +BASE_SECTIONS = ("version", "mesh", "blend", "rasterizer", "depth_stencil", "rt_formats", + "depth_format", "samples") +OPTIONAL_SECTIONS = {"pixel": 2, "constant": 3, "views": 4, "heap_sgpr": 5} +METADATA = ("review_required", "provenance", "capture") + + +def require_fields(record, names, label): + """Exact object keys, reused by the reviewer and the draft tests.""" + 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 analyze(archive): + variant, parts = read_creation(archive) + desc, block_a, block_b, root, ms, ps = parts + validate_stage_lengths(root, ms, ps) + sidecar = archive.with_suffix(".t57") + captured, stencil_ref, observations = read_captured_state(sidecar, block_a, ps, require_mesh_layout=True) + stage = classify_pixel(ps) + issues = stage_consistency(stage, captured["depth_stencil"], observations, ps) + return dict(variant=variant, parts=parts, block_a=block_a, block_b=block_b, root=root, ms=ms, ps=ps, + sidecar=sidecar, captured=captured, stencil_ref=stencil_ref, observations=observations, + stage=stage, issues=issues) + + +def record_provenance(provenance, path, value, source, reason): + if isinstance(value, dict): + for name, field in value.items(): + record_provenance(provenance, f"{path}.{name}", field, source, reason) + else: + provenance[path] = {"source": source, "reason": reason} + + +def draft_blend(blend, ps, sidecar, provenance): + independent, targets = blend["independent"], blend["targets"] + unlocated = "not located in the capture" + record_provenance(provenance, "blend.alpha_to_coverage", None, None, unlocated) + record_provenance(provenance, "blend.independent", independent, f"state block A and {sidecar.name}", + "Compared decoded blend controls for the selected render targets.") + if not targets: + source, reason = ((sidecar.name, "Observed zero render targets.") if ps else + (".ps57", "The pixel shader is empty.")) + record_provenance(provenance, "blend.targets", targets, source, reason) + for index, target in enumerate(targets): + path = f"blend.targets[{index}]" + offset = MESH_BLEND_OFFSET + 4 * index + record_provenance(provenance, path, target, f"state block A +0x{offset:X} (layout 6)", + f"Decoded CB_BLEND{index}_CONTROL.") + missing = dict(write_mask=None, logic_op=None, logic_op_enable=None) + record_provenance(provenance, path, missing, None, unlocated) + target.update(missing) + return dict(alpha_to_coverage=None, independent=independent, targets=targets) + + +def build_draft(archive): + analysis = analyze(archive) + if analysis["issues"]: + raise ValueError("capture is inconsistent: " + "; ".join(analysis["issues"])) + captured = analysis["captured"] + observations = analysis["observations"] + sidecar = analysis["sidecar"] + ps = analysis["ps"] + depth_stencil = captured["depth_stencil"] + draft = { + "version": None, + "mesh": dict.fromkeys(MESH_FIELDS.split()), + "blend": None, + "rasterizer": dict.fromkeys(RASTERIZER_FIELDS.split()), + "depth_stencil": depth_stencil, + "rt_formats": None, + "depth_format": None, + "samples": {"count": None, "quality": None, "mask": None}, + "pixel": dict.fromkeys(PIXEL_FIELDS.split()), + "constant": dict.fromkeys(CONSTANT_FIELDS.split()), + "views": None, + "heap_sgpr": None, + "review_required": True, + "capture": { + "pixel_stage": analysis["stage"]["kind"], + "color_targets": analysis["stage"]["color_targets"], + "depth_export": analysis["stage"]["depth_export"], + "sidecar": sidecar.exists(), + "rtv_count": None if observations is None else len(observations[0]), + "depth_writable": None if observations is None else observations[2], + "sample_count": None if observations is None else observations[3], + "sample_quality": None if observations is None else observations[4], + }, + } + provenance = {} + unresolved = { + "version": "Review the creation root and entry mappings to select a version.", + "mesh": "Review mesh entry metadata and topology.", + "rasterizer": "The capture has no established rasterizer field mapping.", + "pixel": "Review pixel entry metadata if the chosen version requires it.", + "constant": "Review root constant mapping if the chosen version requires it.", + "views": "Review root view mappings if the chosen version requires them.", + "heap_sgpr": "Review the resource heap mapping if the chosen version requires it.", + } + if not ps: + draft["pixel"] = dict(enable=0, address=0, wave_size=0) + unresolved["pixel"] = "The .ps57 is empty; versions 2-5 require a zeroed pixel entry." + for section, reason in unresolved.items(): + record_provenance(provenance, section, draft[section], None, reason) + record_provenance(provenance, "depth_stencil", depth_stencil, "state block A +0x10C..+0x118 (layout 6)", + "Decoded DB_DEPTH_CONTROL, DB_STENCIL_CONTROL and DB_STENCILREFMASK/_BF.") + if analysis["stencil_ref"] is not None: + provenance["depth_stencil.stencil_enable"]["reason"] += ( + f" The captured reference is 0x{analysis['stencil_ref']:02x}. " + "Verify the native draw uses this command-list reference.") + if observations is None: + for field in ("blend", "rt_formats", "depth_format", "samples.count", "samples.quality"): + provenance[field] = {"source": sidecar.name, "reason": "No attachment tuple was observed."} + else: + rtvs, _, writable, _, _ = observations + draft["blend"] = draft_blend(captured["blend"], ps, sidecar, provenance) + draft["rt_formats"] = captured["rt_formats"] + draft["depth_format"] = captured["depth_format"] + draft["samples"].update(captured["samples"]) + provenance["rt_formats"] = {"source": sidecar.name, "reason": f"Observed {len(rtvs)} ordered RTV formats."} + provenance["depth_format"] = {"source": sidecar.name, "reason": f"Observed DSV format with writable={writable}."} + for field in ("samples.count", "samples.quality"): + provenance[field] = {"source": sidecar.name, "reason": "Observed resource sample description."} + provenance["samples.mask"] = {"source": None, + "reason": "Resource sample descriptions omit the pipeline sample mask."} + draft["provenance"] = provenance + return draft + + +def object_issues(value, path, fields): + if value is None: + return [f"{path} is null"] + if not isinstance(value, dict): + return [f"{path} must be an object"] + required = set(fields.split()) + issues = [f"{path} is missing {name}" for name in sorted(required - value.keys())] + issues += [f"{path} has unexpected field {name}" for name in sorted(value.keys() - required)] + for name in fields.split(): + if name in value and value[name] is None: + issues.append(f"{path}.{name} is null") + return issues + + +def review_issues(archive, state): + """Every reason the record is not a complete reviewed profile, not just the first.""" + if not isinstance(state, dict): + return ["profile must be an object"] + issues = [] + for name in METADATA: + if name in state: + issues.append("review_required marker still present" if name == "review_required" + else f"review metadata still present: {name}") + version = state.get("version") + if version is None: + issues.append("profile.version is null") + elif type(version) is not int or not 1 <= version <= 6: + issues.append("profile.version must be an integer 1 through 6") + known = set(BASE_SECTIONS) | set(OPTIONAL_SECTIONS) | set(METADATA) + issues += [f"profile has unexpected field {name}" for name in sorted(state.keys() - known)] + # Base sections are always required once a version is chosen. Before that, report + # their nulls too: the version cannot make a missing mesh or depth state valid. + for name in BASE_SECTIONS[1:]: + value = state.get(name, "__missing__") + if value == "__missing__": + issues.append(f"profile is missing {name}") + elif name == "blend": + issues += blend_issues(value) + elif name == "depth_stencil": + issues += depth_issues(value) + elif name == "mesh": + issues += object_issues(value, "profile.mesh", MESH_FIELDS) + elif name == "rasterizer": + issues += object_issues(value, "profile.rasterizer", RASTERIZER_FIELDS) + elif name == "samples": + issues += object_issues(value, "profile.samples", "count quality mask") + elif name == "rt_formats": + if value is None: + issues.append("profile.rt_formats is null") + elif not isinstance(value, list): + issues.append("profile.rt_formats must be a list") + else: + issues += [f"profile.rt_formats[{index}] is null" for index, item in enumerate(value) if item is None] + elif name == "depth_format" and value is None: + issues.append("profile.depth_format is null") + if type(version) is int and 1 <= version <= 6: + required_optional = {name for name, first in OPTIONAL_SECTIONS.items() if version >= first} + for name in sorted(required_optional - set(state.keys())): + issues.append(f"profile is missing {name}") + for name, first in OPTIONAL_SECTIONS.items(): + if version < first and name in state: + issues.append(f"profile.{name} is unused in version {version}; remove it") + elif version >= first and name in state: + if name == "pixel": + issues += object_issues(state[name], "profile.pixel", PIXEL_FIELDS) + elif name == "constant": + issues += object_issues(state[name], "profile.constant", CONSTANT_FIELDS) + elif name == "views": + views = state[name] + if views is None: + issues.append("profile.views is null") + elif not isinstance(views, list): + issues.append("profile.views must be a list") + else: + for index, view in enumerate(views): + issues += object_issues(view, f"profile.views[{index}]", "sgpr root_parameter root_address") + elif name == "heap_sgpr" and state[name] is None: + issues.append("profile.heap_sgpr is null") + issues = [issue for issue in issues if issue] + if issues: + return issues + try: + _, parts = read_creation(archive) + captured, _, _ = read_captured_state(archive.with_suffix(".t57"), parts[1], parts[5]) + except (OSError, ValueError, Unsupported, struct.error) as error: + return [str(error)] + for section, value in captured.items(): + if section in state: + issues += [f"reviewed state disagrees with capture: {path}" + for path in capture_mismatches(value, state[section], section)] + if issues: + return issues + try: + build_profile(archive, state) + except (OSError, ValueError, Unsupported, struct.error) as error: + return [str(error)] + return [] + + +def blend_issues(value): + if value is None: + return ["profile.blend is null"] + if not isinstance(value, dict): + return ["profile.blend must be an object"] + issues = object_issues({k: v for k, v in value.items() if k != "targets"}, "profile.blend", + "alpha_to_coverage independent") + targets = value.get("targets") + if targets is None: + issues.append("profile.blend.targets is null") + elif not isinstance(targets, list): + issues.append("profile.blend.targets must be a list") + else: + for index, target in enumerate(targets): + issues += object_issues(target, f"profile.blend.targets[{index}]", BLEND_TARGET_FIELDS) + return issues + + +def depth_issues(value): + fields = "depth_enable depth_write_mask depth_func stencil_enable stencil_read_mask stencil_write_mask" + if value is None: + return ["profile.depth_stencil is null"] + if not isinstance(value, dict): + return ["profile.depth_stencil must be an object"] + issues = object_issues(value, "profile.depth_stencil", fields + " front_face back_face") + for face in ("front_face", "back_face"): + if value.get(face) is not None: + issues += object_issues(value[face], f"profile.depth_stencil.{face}", "fail depth_fail pass func") + return issues + + +def draft_main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("--draft", action="store_true", help="write a new review JSON from a capture") + group.add_argument("--check", action="store_true", help="list unresolved fields and capture disagreements") + group.add_argument("--census", type=Path, help="summarize captures in a directory without writing") + parser.add_argument("archive", type=Path, nargs="?", help="req_.s57 beside its .m57, .ps57 and .root") + parser.add_argument("json", type=Path, nargs="?", help="draft output or reviewed input") + parser.add_argument("--verbose", action="store_true", help="census: print one line per capture") + args = parser.parse_args(argv) + try: + if args.census is not None: + if args.archive is not None or args.json is not None: + parser.error("--census takes only a directory") + return census(args.census, args.verbose) + if args.archive is None or args.json is None: + parser.error("--draft and --check take ARCHIVE JSON") + if args.draft: + draft = build_draft(args.archive) + with args.json.open("x", encoding="utf-8", newline="\n") as stream: + stream.write(json.dumps(draft, indent=2) + "\n") + print(args.json) + return 0 + with args.json.open(encoding="utf-8") as stream: + state = json.load(stream, object_pairs_hook=unique_fields) + issues = review_issues(args.archive, state) + if issues: + print("profile incomplete:") + for issue in issues: + print(f" - {issue}") + return 1 + name, _ = build_profile(args.archive, state) + print(f"profile complete: {name}") + return 0 + except (OSError, ValueError, Unsupported, struct.error) as error: + print(error, file=sys.stderr) + return 1 + + +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 census(directory, verbose=False): + files = sorted(directory.glob("req_*.s57")) + counts = {name: 0 for name in ("color", "depth", "null", "none", "param", "empty", "refused")} + sidecars = attachment_known = consistent = 0 + rows = [] + for path in files: + try: + analysis = analyze(path) + except (OSError, ValueError, Unsupported, struct.error) as error: + counts["refused"] += 1 + rows.append(f"{path.name}\trefused\t{error}") + continue + counts[analysis["stage"]["kind"]] += 1 + if analysis["sidecar"].exists(): + sidecars += 1 + observations = analysis["observations"] + rtv = "?" if observations is None else len(observations[0]) + dsv = "?" if observations is None else observations[1] + if observations is not None: + attachment_known += 1 + if not analysis["issues"]: + consistent += 1 + rows.append( + f"{path.name}\t{analysis['stage']['kind']}\trtv={rtv}\tdsv={dsv}" + f"\tsidecar={int(analysis['sidecar'].exists())}\tdepth={analysis['captured']['depth_stencil']['depth_enable']}/" + f"{analysis['captured']['depth_stencil']['depth_write_mask']}" + f"\tconsistent={int(observations is not None and not analysis['issues'])}") + for row in rows: + if verbose: + print(row) + print(f"captures {len(files)}: color {counts['color']}, depth {counts['depth']}, null {counts['null']}, " + f"param {counts['param']}, none {counts['none']}, empty {counts['empty']}, refused {counts['refused']}") + print(f"sidecars {sidecars}, attachment tuples {attachment_known}, " + f"consistent stage/attachment pairs {consistent}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(draft_main())