gfx2hlsl: lower 2D depth-comparison image sampling (image_sample_c, image_sample_c_lz) #1464

Merged
tedin7 merged 4 commits from upstream-pr/1471 into main 2026-11-24 13:48:16 +00:00
tedin7 commented 2026-11-24 12:17:28 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T12:17:28Z.


Change

tools/startup/gfx2hlsl.py lowers the gfx1013 image_sample_c_lz and image_sample_c forms of a 2D texture (dmask:0x1) to SampleCmpLevelZero (and SampleCmp for image_sample_c in a pixel stage with a known execution mask and no branches). The first address register is the reference, then u and v. The sampler words must pass the existing pixel_aot.comparison_sampler_state profile; the sampler is declared as a SamplerComparisonState and listed as an smpc N w0 w1 w2 w3 manifest line. src/startup_stubs/translated_sampler_bindings.h builds the matching comparison static sampler (filter 0x80 or 0x94, function = hardware function + 1) and keeps manifest order as register order.

image_sample_c_l is refused (HLSL has no SampleCmpLevel before shader model 6.7; the stages compile as 5.1 and 6.0). Array, 3D, cube and 1D images, other dmask values, offset/bias/clamp/gather forms, a16/d16/tfe/lwe/r128/unorm, reserved MIMG bits, run-time heap samplers and samplers outside the checked profile are refused with their own message.

Draft: a D3D12 readback of a gfx2hlsl.py comparison draw is not part of this PR (see Evidence and follow-up).

Verification

AI-assisted; commands listed were executed locally (Linux, Python 3, LLVM 15.0.6 extracted from the Debian package into a temporary folder, and LLVM 19).

  • python3 -B tests/startup_image_sample_c_check.py: all controls and 7 mutants pass/fail as expected.
  • python3 -B tests/startup_image_sample_c_check.py binary llvm-mc-15 and ... binary llvm-mc-19: fixture words match llvm-mc (every recorded fixture, both LLVM versions).
  • Same test on origin/main (detached copy of main): fails with gfx2hlsl.Unsupported: image_sample_c_lz.
  • x86_64-w64-mingw32-g++ -std=c++17 -Wall -Wextra of tests/startup_sampler_comparison_check.cpp, run under Wine: startup_sampler_comparison ok. Mutating the header (function offset, filter reduction, smpc parsing) makes it print FAIL for each.
  • tests/startup_image_sample_l_check.py, startup_image_3d_check.py, startup_image_load_mip_check.py, startup_image_2d_array_check.py, startup_flat_param_check.py, startup_gfx2hlsl_bit_alu_check.py, startup_gfx2hlsl_sdwa_check.py, startup_inline_sampler_check.py, startup_sampler_heap_check.py, startup_translator_check.py, docs_links_check.py, bidi_controls_check.py: pass. rdna2_tools_check.py with LLVM 15: OK (skipped=1). py_compile and git diff --check: clean.
  • Not run here (no Windows host): the MSVC build of the new executable and ctest --preset dev --no-tests=error -R '^(startup_image_sample_c|startup_sampler_comparison)$' -V (outside --preset pr; Debug and /O2).

Evidence and follow-up

  • Fixtures are source-built gfx1013 assembly in the test; nothing is copied from a game or a dump.
  • Order of the address registers: the contiguous form v[0:2] reads the reference from v0, the NSA form [v3, v0, v1] reads it from v3. The same image_sample_c_lz order and the same HLSL call are already read back on WARP for the pixel AOT path by tests/pixel_compare_check.py.
  • Missing: a WARP/hardware draw that runs the gfx2hlsl.py output with an smpc sampler on an R32_FLOAT texture and checks exact 1.0/0.0 per comparison function. Also open: 2D array comparisons and image_sample_c_l (needs a proven constant level 0 or shader model 6.7).
  • Overlap: touches CMakeLists.txt, docs/experiments.md and windows.yml only with appended entries; tools/startup/gfx2hlsl.py hunks are separate from #1430 (a merge of both is clean).

Checklist

  • This pull request covers one reviewable behavior.
  • I included the exact command and result for every check I ran.
  • I considered a negative control or failure case for a new fixture.
  • I updated README/docs when a capability or build requirement changed.
  • I did not include game files, dumps, distribution links or secrets.
<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6581593622 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1471). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T12:17:28Z. --- ## Change `tools/startup/gfx2hlsl.py` lowers the gfx1013 `image_sample_c_lz` and `image_sample_c` forms of a 2D texture (`dmask:0x1`) to `SampleCmpLevelZero` (and `SampleCmp` for `image_sample_c` in a pixel stage with a known execution mask and no branches). The first address register is the reference, then u and v. The sampler words must pass the existing `pixel_aot.comparison_sampler_state` profile; the sampler is declared as a `SamplerComparisonState` and listed as an `smpc N w0 w1 w2 w3` manifest line. `src/startup_stubs/translated_sampler_bindings.h` builds the matching comparison static sampler (filter 0x80 or 0x94, function = hardware function + 1) and keeps manifest order as register order. `image_sample_c_l` is refused (HLSL has no `SampleCmpLevel` before shader model 6.7; the stages compile as 5.1 and 6.0). Array, 3D, cube and 1D images, other `dmask` values, offset/bias/clamp/gather forms, `a16`/`d16`/`tfe`/`lwe`/`r128`/`unorm`, reserved MIMG bits, run-time heap samplers and samplers outside the checked profile are refused with their own message. Draft: a D3D12 readback of a `gfx2hlsl.py` comparison draw is not part of this PR (see Evidence and follow-up). ## Verification AI-assisted; commands listed were executed locally (Linux, Python 3, LLVM 15.0.6 extracted from the Debian package into a temporary folder, and LLVM 19). - `python3 -B tests/startup_image_sample_c_check.py`: all controls and 7 mutants pass/fail as expected. - `python3 -B tests/startup_image_sample_c_check.py binary llvm-mc-15` and `... binary llvm-mc-19`: `fixture words match llvm-mc` (every recorded fixture, both LLVM versions). - Same test on `origin/main` (detached copy of main): fails with `gfx2hlsl.Unsupported: image_sample_c_lz`. - `x86_64-w64-mingw32-g++ -std=c++17 -Wall -Wextra` of `tests/startup_sampler_comparison_check.cpp`, run under Wine: `startup_sampler_comparison ok`. Mutating the header (function offset, filter reduction, `smpc` parsing) makes it print `FAIL` for each. - `tests/startup_image_sample_l_check.py`, `startup_image_3d_check.py`, `startup_image_load_mip_check.py`, `startup_image_2d_array_check.py`, `startup_flat_param_check.py`, `startup_gfx2hlsl_bit_alu_check.py`, `startup_gfx2hlsl_sdwa_check.py`, `startup_inline_sampler_check.py`, `startup_sampler_heap_check.py`, `startup_translator_check.py`, `docs_links_check.py`, `bidi_controls_check.py`: pass. `rdna2_tools_check.py` with LLVM 15: `OK (skipped=1)`. `py_compile` and `git diff --check`: clean. - Not run here (no Windows host): the MSVC build of the new executable and `ctest --preset dev --no-tests=error -R '^(startup_image_sample_c|startup_sampler_comparison)$' -V` (outside `--preset pr`; Debug and /O2). ## Evidence and follow-up - Fixtures are source-built gfx1013 assembly in the test; nothing is copied from a game or a dump. - Order of the address registers: the contiguous form `v[0:2]` reads the reference from `v0`, the NSA form `[v3, v0, v1]` reads it from `v3`. The same `image_sample_c_lz` order and the same HLSL call are already read back on WARP for the pixel AOT path by `tests/pixel_compare_check.py`. - Missing: a WARP/hardware draw that runs the `gfx2hlsl.py` output with an `smpc` sampler on an R32_FLOAT texture and checks exact 1.0/0.0 per comparison function. Also open: 2D array comparisons and `image_sample_c_l` (needs a proven constant level 0 or shader model 6.7). - Overlap: touches `CMakeLists.txt`, `docs/experiments.md` and `windows.yml` only with appended entries; `tools/startup/gfx2hlsl.py` hunks are separate from #1430 (a merge of both is clean). ## Checklist - [x] This pull request covers one reviewable behavior. - [x] I included the exact command and result for every check I ran. - [x] I considered a negative control or failure case for a new fixture. - [x] I updated README/docs when a capability or build requirement changed. - [x] I did not include game files, dumps, distribution links or secrets.
chatgpt-codex-connector[bot commented 2026-11-24 13:00:41 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T12:31:39Z.

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5b91c08744

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6039230644 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1471#pullrequestreview-6039230644). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T12:31:39Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `5b91c08744` <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review". If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". </details>
tedin7 commented 2026-11-24 13:00:41 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T12:43:23Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6039389185 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1471#pullrequestreview-6039389185). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T12:43:23Z. **Review:** COMMENTED --- _No description provided._
tedin7 commented 2026-11-24 13:00:53 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T12:26:30Z.


Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP) at commit 5b91c08744114cde5789189dc0fa152461dde4f9:

  • Debug (--preset dev): ctest --preset dev -R '^(startup_sampler_comparison|startup_image_sample_c)$' --no-tests=error --output-on-failure: 2/2 passed
  • Release /O2 (--preset release): same selection: 2/2 passed

Linux: git diff --check, docs_links_check.py, bidi_controls_check.py and x2w_pipe.py preflight pass.

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7131443542 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1471#issuecomment-7131443542). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T12:26:30Z. --- Verified on Windows Server 2025 (Build 26100, MSVC 14.44.35207 + D3D12 WARP) at commit `5b91c08744114cde5789189dc0fa152461dde4f9`: - **Debug (`--preset dev`)**: `ctest --preset dev -R '^(startup_sampler_comparison|startup_image_sample_c)$' --no-tests=error --output-on-failure`: **2/2 passed** - **Release `/O2` (`--preset release`)**: same selection: **2/2 passed** Linux: `git diff --check`, `docs_links_check.py`, `bidi_controls_check.py` and `x2w_pipe.py preflight` pass. AI-assisted; commands listed were executed locally.
chatgpt-codex-connector[bot commented 2026-11-24 13:00:53 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T12:26:41Z.


Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-24T12:31:41.963440Z 5b91c08 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7131447885 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1471#issuecomment-7131447885). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T12:26:41Z. --- <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"5b91c08744114cde5789189dc0fa152461dde4f9","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} --> <details> <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary> This comment shows the latest Codex review activity on this pull request. | Review | Status | Commit | Review trigger | | --- | --- | --- | --- | | 📝 **Code Review** | ✅ **Completed** <relative-time datetime="2026-11-24T12:31:41.963440Z">2026-11-24T12:31:41.963440Z</relative-time> | `5b91c08` | Draft marked ready | <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review" or "@codex security review". Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. </details> </details>
chatgpt-codex-connector[bot commented 2026-11-24 13:00:57 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T12:31:39Z.

Code review location: tools/startup/gfx2hlsl.py; line 795

@@ -742,6 +742,70 @@ def image(self, ops, mods, how):
                 self.set_v(n, 'U(t.%s)' % comp)
                 n += 1
 
+    def image_compare(self, ops, mods, how):
+        """image_sample_c and image_sample_c_lz: a 2D depth comparison returning one float.
+
+        The address dwords are the reference, then u and v, which is what SampleCmp* takes as its third
+        argument and its location. The comparison function and the filter live in the sampler descriptor,
+        so they are read from its constant words by the decoder the pixel AOT path already checks against
+        D3D12 (pixel_aot.comparison_sampler_state) and bound as a SamplerComparisonState. HLSL has no
+        SampleCmpLevel before shader model 6.7 (the stages here compile as 5.1 and 6.0), so
+        image_sample_c_l is refused instead of being sampled at level zero.
+        """
+        base = 'image_sample_' + how
+        if how == 'c_l':
+            raise Unsupported('image_sample_c_l: SampleCmpLevel needs shader model 6.7; only c and c_lz are lowered')
+        for m in mods:
+            if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')):
+                raise Unsupported('%s modifier %s' % (base, m))
+        dims = [m[4:] for m in mods if m.startswith('dim:')]
+        masks = [m[6:] for m in mods if m.startswith('dmask:')]
+        if len(dims) != 1 or len(masks) != 1:
+            raise Unsupported('%s without exactly one dim and dmask' % base)
+        dim, dmask = dims[0], int(masks[0], 0)
+        if dim != 'SQ_RSRC_IMG_2D':
+            raise Unsupported('%s on %s' % (base, dim))
+        if dmask != 1:
+            raise Unsupported('%s with dmask %#x: a comparison returns one channel' % (base, dmask))
+        if len(ops) != 4:
+            raise Unsupported('%s with %d operands' % (base, len(ops)))
+        coords = ops[1]
+        if coords.startswith('['):
+            cs = [c.strip() for c in coords[1:-1].split(',')]
+        else:
+            r = reg_range(coords)
+            cs = ['v%d' % n for n in range(r[1], r[2] + 1)]
+        if len(cs) != 3:
+            raise Unsupported('%s with %d address registers' % (base, len(cs)))
+        if self.heap_sampler(ops[3]):
+            raise Unsupported('%s through a sampler heap' % base)
+        words = self.const_words(ops[3])
+        if words is None:
+            raise Unsupported('%s with a sampler that is not constant' % base)
+        import pixel_aot
+        try:
+            pixel_aot.comparison_sampler_state(tuple(words))
+        except ValueError as error:
+            raise Unsupported('%s sampler: %s' % (base, error))
+        tex = self.pipe.resource(self.descriptor(ops[2]), 'tex2d')
+        smp = self.pipe.sampler(tuple(words), comparison=True)
+        args = '%s, float2(%s, %s), %s' % (smp, self.f(cs[1]), self.f(cs[2]), self.f(cs[0]))
+        # Implicit derivatives exist only in a pixel stage, as for image_sample.
+        if how == 'c' and self.exec_known and self.kind == 'ps' and len(self.blocks) == 0:
+            call = '%s.SampleCmp(%s)' % (tex, args)

P2 Badge Preserve MAX_LOD for implicit depth comparisons

When image_sample_c samples a minified, mipmapped texture with MAX_LOD == 0 (for example, the accepted sampler w1 = 0, w2 = 1 << 26), this emits a derivative-based SampleCmp without preserving that limit. pixel_aot.comparison_sampler_state() deliberately ignores MAX_LOD because its profile validates LOD-zero sampling, while translated_sampler_bindings.h::decode_sampler() always sets MaxLOD to D3D12_FLOAT32_MAX. The source therefore samples mip 0 while the translation can compare against a higher mip, producing different comparison results when the mip contents differ. Decode and enforce the limit for implicit comparisons, or refuse that form until an appropriate sampler profile is supported.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4680010525 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1471#discussion_r4680010525). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T12:31:39Z. **Code review location:** `tools/startup/gfx2hlsl.py`; line 795 ~~~~diff @@ -742,6 +742,70 @@ def image(self, ops, mods, how): self.set_v(n, 'U(t.%s)' % comp) n += 1 + def image_compare(self, ops, mods, how): + """image_sample_c and image_sample_c_lz: a 2D depth comparison returning one float. + + The address dwords are the reference, then u and v, which is what SampleCmp* takes as its third + argument and its location. The comparison function and the filter live in the sampler descriptor, + so they are read from its constant words by the decoder the pixel AOT path already checks against + D3D12 (pixel_aot.comparison_sampler_state) and bound as a SamplerComparisonState. HLSL has no + SampleCmpLevel before shader model 6.7 (the stages here compile as 5.1 and 6.0), so + image_sample_c_l is refused instead of being sampled at level zero. + """ + base = 'image_sample_' + how + if how == 'c_l': + raise Unsupported('image_sample_c_l: SampleCmpLevel needs shader model 6.7; only c and c_lz are lowered') + for m in mods: + if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): + raise Unsupported('%s modifier %s' % (base, m)) + dims = [m[4:] for m in mods if m.startswith('dim:')] + masks = [m[6:] for m in mods if m.startswith('dmask:')] + if len(dims) != 1 or len(masks) != 1: + raise Unsupported('%s without exactly one dim and dmask' % base) + dim, dmask = dims[0], int(masks[0], 0) + if dim != 'SQ_RSRC_IMG_2D': + raise Unsupported('%s on %s' % (base, dim)) + if dmask != 1: + raise Unsupported('%s with dmask %#x: a comparison returns one channel' % (base, dmask)) + if len(ops) != 4: + raise Unsupported('%s with %d operands' % (base, len(ops))) + coords = ops[1] + if coords.startswith('['): + cs = [c.strip() for c in coords[1:-1].split(',')] + else: + r = reg_range(coords) + cs = ['v%d' % n for n in range(r[1], r[2] + 1)] + if len(cs) != 3: + raise Unsupported('%s with %d address registers' % (base, len(cs))) + if self.heap_sampler(ops[3]): + raise Unsupported('%s through a sampler heap' % base) + words = self.const_words(ops[3]) + if words is None: + raise Unsupported('%s with a sampler that is not constant' % base) + import pixel_aot + try: + pixel_aot.comparison_sampler_state(tuple(words)) + except ValueError as error: + raise Unsupported('%s sampler: %s' % (base, error)) + tex = self.pipe.resource(self.descriptor(ops[2]), 'tex2d') + smp = self.pipe.sampler(tuple(words), comparison=True) + args = '%s, float2(%s, %s), %s' % (smp, self.f(cs[1]), self.f(cs[2]), self.f(cs[0])) + # Implicit derivatives exist only in a pixel stage, as for image_sample. + if how == 'c' and self.exec_known and self.kind == 'ps' and len(self.blocks) == 0: + call = '%s.SampleCmp(%s)' % (tex, args) ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Preserve MAX_LOD for implicit depth comparisons** When `image_sample_c` samples a minified, mipmapped texture with `MAX_LOD == 0` (for example, the accepted sampler `w1 = 0, w2 = 1 << 26`), this emits a derivative-based `SampleCmp` without preserving that limit. `pixel_aot.comparison_sampler_state()` deliberately ignores `MAX_LOD` because its profile validates LOD-zero sampling, while `translated_sampler_bindings.h::decode_sampler()` always sets `MaxLOD` to `D3D12_FLOAT32_MAX`. The source therefore samples mip 0 while the translation can compare against a higher mip, producing different comparison results when the mip contents differ. Decode and enforce the limit for implicit comparisons, or refuse that form until an appropriate sampler profile is supported. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
tedin7 commented 2026-11-24 13:00:57 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T12:43:23Z.

Code review location: tools/startup/gfx2hlsl.py; line 795

@@ -742,6 +742,70 @@ def image(self, ops, mods, how):
                 self.set_v(n, 'U(t.%s)' % comp)
                 n += 1
 
+    def image_compare(self, ops, mods, how):
+        """image_sample_c and image_sample_c_lz: a 2D depth comparison returning one float.
+
+        The address dwords are the reference, then u and v, which is what SampleCmp* takes as its third
+        argument and its location. The comparison function and the filter live in the sampler descriptor,
+        so they are read from its constant words by the decoder the pixel AOT path already checks against
+        D3D12 (pixel_aot.comparison_sampler_state) and bound as a SamplerComparisonState. HLSL has no
+        SampleCmpLevel before shader model 6.7 (the stages here compile as 5.1 and 6.0), so
+        image_sample_c_l is refused instead of being sampled at level zero.
+        """
+        base = 'image_sample_' + how
+        if how == 'c_l':
+            raise Unsupported('image_sample_c_l: SampleCmpLevel needs shader model 6.7; only c and c_lz are lowered')
+        for m in mods:
+            if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')):
+                raise Unsupported('%s modifier %s' % (base, m))
+        dims = [m[4:] for m in mods if m.startswith('dim:')]
+        masks = [m[6:] for m in mods if m.startswith('dmask:')]
+        if len(dims) != 1 or len(masks) != 1:
+            raise Unsupported('%s without exactly one dim and dmask' % base)
+        dim, dmask = dims[0], int(masks[0], 0)
+        if dim != 'SQ_RSRC_IMG_2D':
+            raise Unsupported('%s on %s' % (base, dim))
+        if dmask != 1:
+            raise Unsupported('%s with dmask %#x: a comparison returns one channel' % (base, dmask))
+        if len(ops) != 4:
+            raise Unsupported('%s with %d operands' % (base, len(ops)))
+        coords = ops[1]
+        if coords.startswith('['):
+            cs = [c.strip() for c in coords[1:-1].split(',')]
+        else:
+            r = reg_range(coords)
+            cs = ['v%d' % n for n in range(r[1], r[2] + 1)]
+        if len(cs) != 3:
+            raise Unsupported('%s with %d address registers' % (base, len(cs)))
+        if self.heap_sampler(ops[3]):
+            raise Unsupported('%s through a sampler heap' % base)
+        words = self.const_words(ops[3])
+        if words is None:
+            raise Unsupported('%s with a sampler that is not constant' % base)
+        import pixel_aot
+        try:
+            pixel_aot.comparison_sampler_state(tuple(words))
+        except ValueError as error:
+            raise Unsupported('%s sampler: %s' % (base, error))
+        tex = self.pipe.resource(self.descriptor(ops[2]), 'tex2d')
+        smp = self.pipe.sampler(tuple(words), comparison=True)
+        args = '%s, float2(%s, %s), %s' % (smp, self.f(cs[1]), self.f(cs[2]), self.f(cs[0]))
+        # Implicit derivatives exist only in a pixel stage, as for image_sample.
+        if how == 'c' and self.exec_known and self.kind == 'ps' and len(self.blocks) == 0:
+            call = '%s.SampleCmp(%s)' % (tex, args)

Fixed in 8ae3c180: an implicit comparison now reads MAX_LOD (word 1 bits 23:12). A limit of 0 lowers to SampleCmpLevelZero, which is exact. The unlimited value keeps SampleCmp. Any other limit is refused, because the static sampler cannot carry it. New fixtures c_max0 and c_max_partial in tests/startup_image_sample_c_check.py cover both cases.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4680139204 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1471#discussion_r4680139204). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T12:43:23Z. **Code review location:** `tools/startup/gfx2hlsl.py`; line 795 ~~~~diff @@ -742,6 +742,70 @@ def image(self, ops, mods, how): self.set_v(n, 'U(t.%s)' % comp) n += 1 + def image_compare(self, ops, mods, how): + """image_sample_c and image_sample_c_lz: a 2D depth comparison returning one float. + + The address dwords are the reference, then u and v, which is what SampleCmp* takes as its third + argument and its location. The comparison function and the filter live in the sampler descriptor, + so they are read from its constant words by the decoder the pixel AOT path already checks against + D3D12 (pixel_aot.comparison_sampler_state) and bound as a SamplerComparisonState. HLSL has no + SampleCmpLevel before shader model 6.7 (the stages here compile as 5.1 and 6.0), so + image_sample_c_l is refused instead of being sampled at level zero. + """ + base = 'image_sample_' + how + if how == 'c_l': + raise Unsupported('image_sample_c_l: SampleCmpLevel needs shader model 6.7; only c and c_lz are lowered') + for m in mods: + if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): + raise Unsupported('%s modifier %s' % (base, m)) + dims = [m[4:] for m in mods if m.startswith('dim:')] + masks = [m[6:] for m in mods if m.startswith('dmask:')] + if len(dims) != 1 or len(masks) != 1: + raise Unsupported('%s without exactly one dim and dmask' % base) + dim, dmask = dims[0], int(masks[0], 0) + if dim != 'SQ_RSRC_IMG_2D': + raise Unsupported('%s on %s' % (base, dim)) + if dmask != 1: + raise Unsupported('%s with dmask %#x: a comparison returns one channel' % (base, dmask)) + if len(ops) != 4: + raise Unsupported('%s with %d operands' % (base, len(ops))) + coords = ops[1] + if coords.startswith('['): + cs = [c.strip() for c in coords[1:-1].split(',')] + else: + r = reg_range(coords) + cs = ['v%d' % n for n in range(r[1], r[2] + 1)] + if len(cs) != 3: + raise Unsupported('%s with %d address registers' % (base, len(cs))) + if self.heap_sampler(ops[3]): + raise Unsupported('%s through a sampler heap' % base) + words = self.const_words(ops[3]) + if words is None: + raise Unsupported('%s with a sampler that is not constant' % base) + import pixel_aot + try: + pixel_aot.comparison_sampler_state(tuple(words)) + except ValueError as error: + raise Unsupported('%s sampler: %s' % (base, error)) + tex = self.pipe.resource(self.descriptor(ops[2]), 'tex2d') + smp = self.pipe.sampler(tuple(words), comparison=True) + args = '%s, float2(%s, %s), %s' % (smp, self.f(cs[1]), self.f(cs[2]), self.f(cs[0])) + # Implicit derivatives exist only in a pixel stage, as for image_sample. + if how == 'c' and self.exec_known and self.kind == 'ps' and len(self.blocks) == 0: + call = '%s.SampleCmp(%s)' % (tex, args) ~~~~ --- Fixed in 8ae3c180: an implicit comparison now reads MAX_LOD (word 1 bits 23:12). A limit of 0 lowers to SampleCmpLevelZero, which is exact. The unlimited value keeps SampleCmp. Any other limit is refused, because the static sampler cannot carry it. New fixtures c_max0 and c_max_partial in tests/startup_image_sample_c_check.py cover both cases.
upstream-sync closed this pull request 2026-11-24 14:02:48 +00:00
R0Y00 commented 2026-11-24 14:02:49 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T13:09:37Z.

Review: CHANGES_REQUESTED


Release passes the three translator/sampler checks. In image_compare, an implicit comparison with unrestricted MAX_LOD falls through to SampleCmpLevelZero when EXEC is uncertain or the sample is inside a block. This silently changes the selected mip. Please refuse that implicit form when its derivatives cannot be represented, while retaining explicit-zero and proven MAX_LOD=0. For the unrestricted branch, please establish the mip filter and chosen mip with two distinguishable mips in a source-built startup draw, or keep the first slice at proven LOD zero.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6039757858 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1471#pullrequestreview-6039757858). Originally posted by [R0Y00](https://github.com/R0Y00) on 2026-11-24T13:09:37Z. **Review:** CHANGES_REQUESTED --- Release passes the three translator/sampler checks. In image_compare, an implicit comparison with unrestricted MAX_LOD falls through to SampleCmpLevelZero when EXEC is uncertain or the sample is inside a block. This silently changes the selected mip. Please refuse that implicit form when its derivatives cannot be represented, while retaining explicit-zero and proven MAX_LOD=0. For the unrestricted branch, please establish the mip filter and chosen mip with two distinguishable mips in a source-built startup draw, or keep the first slice at proven LOD zero.
R0Y00 commented 2026-11-24 14:02:49 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T13:25:41Z.

Review: COMMENTED


The new derivative refusal and three Release checks pass. The unrestricted mip branch still needs its own evidence: the comparison-state helper deliberately ignores the mip filter when mapping to the level-zero desktop profiles, and the shown runtime static sampler filters use point mip selection. Please keep unrestricted implicit sampling out of this slice or add the matched mip-filter mapping and a two-mip startup draw that fails on an incorrect mip or blend.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6039986083 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1471#pullrequestreview-6039986083). Originally posted by [R0Y00](https://github.com/R0Y00) on 2026-11-24T13:25:41Z. **Review:** COMMENTED --- The new derivative refusal and three Release checks pass. The unrestricted mip branch still needs its own evidence: the comparison-state helper deliberately ignores the mip filter when mapping to the level-zero desktop profiles, and the shown runtime static sampler filters use point mip selection. Please keep unrestricted implicit sampling out of this slice or add the matched mip-filter mapping and a two-mip startup draw that fails on an incorrect mip or blend.
R0Y00 commented 2026-11-24 14:02:49 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-24T13:48:02Z.

Review: APPROVED


Re-reviewed d21e3d6e. The startup translator now limits the first slice to level zero and rejects unrestricted implicit mip selection. The three Release translation and sampler-binding checks passed. This verifies the translator and binding fixture scope.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6040344032 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1471#pullrequestreview-6040344032). Originally posted by [R0Y00](https://github.com/R0Y00) on 2026-11-24T13:48:02Z. **Review:** APPROVED --- Re-reviewed d21e3d6e. The startup translator now limits the first slice to level zero and rejects unrestricted implicit mip selection. The three Release translation and sampler-binding checks passed. This verifies the translator and binding fixture scope.
tedin7 commented 2026-11-24 14:03:23 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T13:13:48Z.


Fixed in d9e27f68: image_compare now refuses an implicit image_sample_c with unrestricted MAX_LOD when its derivatives cannot be represented (exec not proven, or inside a block), instead of falling through to SampleCmpLevelZero. Proven MAX_LOD=0 still lowers to SampleCmpLevelZero, and the proven pixel-stage unrestricted form still lowers to SampleCmp. I did not add a two-mip draw test; the unrestricted SampleCmp form stays limited to the cases where the derivatives are proven.

Regression test in tests/startup_image_sample_c_check.py: both implicit fixtures (c, c_nsa) are refused in the exec-uncertain and in-block cases, and c_max0 stays SampleCmpLevelZero in both.

Win2025 startup_sampler_comparison and startup_image_sample_c on d9e27f68:

  • Debug (--preset dev): 2/2 passed.
  • Release /O2 (--preset release): 2/2 passed.
<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7132531810 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1471#issuecomment-7132531810). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T13:13:48Z. --- Fixed in d9e27f68: `image_compare` now refuses an implicit `image_sample_c` with unrestricted MAX_LOD when its derivatives cannot be represented (exec not proven, or inside a block), instead of falling through to `SampleCmpLevelZero`. Proven MAX_LOD=0 still lowers to `SampleCmpLevelZero`, and the proven pixel-stage unrestricted form still lowers to `SampleCmp`. I did not add a two-mip draw test; the unrestricted `SampleCmp` form stays limited to the cases where the derivatives are proven. Regression test in `tests/startup_image_sample_c_check.py`: both implicit fixtures (`c`, `c_nsa`) are refused in the exec-uncertain and in-block cases, and `c_max0` stays `SampleCmpLevelZero` in both. Win2025 `startup_sampler_comparison` and `startup_image_sample_c` on d9e27f68: - Debug (`--preset dev`): 2/2 passed. - Release `/O2` (`--preset release`): 2/2 passed.
tedin7 commented 2026-11-24 14:03:25 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T13:36:28Z.


Fixed in d21e3d6e: unrestricted implicit image_sample_c is kept out of this slice. image_sample_c is lowered to SampleCmpLevelZero only when the sampler MAX_LOD is 0 (exact level zero); any other MAX_LOD is refused as implicit mip selection, so the SampleCmp branch and its mip-filter-ignoring mapping are gone. tests/startup_image_sample_c_check.py now requires c, c_nsa and the partial-MAX_LOD form to be refused and keeps the MAX_LOD 0 lowering; docs/experiments.md is updated.

Win2025 at d21e3d6e: Debug (dev) startup_sampler_comparison + startup_image_sample_c 2/2 passed; Release /O2 2/2 passed.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7133073188 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1471#issuecomment-7133073188). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T13:36:28Z. --- Fixed in d21e3d6e: unrestricted implicit image_sample_c is kept out of this slice. image_sample_c is lowered to SampleCmpLevelZero only when the sampler MAX_LOD is 0 (exact level zero); any other MAX_LOD is refused as implicit mip selection, so the SampleCmp branch and its mip-filter-ignoring mapping are gone. tests/startup_image_sample_c_check.py now requires c, c_nsa and the partial-MAX_LOD form to be refused and keeps the MAX_LOD 0 lowering; docs/experiments.md is updated. Win2025 at d21e3d6e: Debug (dev) startup_sampler_comparison + startup_image_sample_c 2/2 passed; Release /O2 2/2 passed.
ChazY11 commented 2026-11-24 16:03:32 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by ChazY11 on 2026-11-24T15:11:52Z.


The reference ordering and the comparison call are both covered

Independent reviewer, not the author. Reviewed the current head; nothing pushed to the branch. Mutations were made
locally in tools/startup/gfx2hlsl.py, reverted between each; working tree is clean.

Environment: Windows 11 build 26300.9974, MSVC 14.44.35207, SDK 10.0.26100, DXC 1.8.2502.11, LLVM gfx1013 tooling
available, RTX 5080 Laptop (32.0.15.8142) for _hardware.

cmake --preset dev
cmake --build --preset dev
ctest --preset dev --no-tests=error -R 'sample_c|comparison' -V
startup_sampler_comparison ....... Passed  0.14 s
startup_image_sample_c ........... Passed  0.92 s
pixel_aot_comparisons_hardware ... Passed 41.49 s
pixel_aot_comparisons_warp ....... Passed 11.56 s

Mutation A — the address dwords are unpacked in the wrong order

The lowering builds SampleCmpLevelZero(smp, float2(u, v), reference) from cs[1], cs[2] and cs[0]. Taking the
dwords in file order instead:

-    args = '%s, float2(%s, %s), %s' % (smp, self.f(cs[1]), self.f(cs[2]), self.f(cs[0]))
+    args = '%s, float2(%s, %s), %s' % (smp, self.f(cs[0]), self.f(cs[1]), self.f(cs[2]))
startup_image_sample_c ........... ***Failed
startup_sampler_comparison ....... Passed

So the fixture notices that the reference is the first address dword rather than the first argument slot — which is the
easy mistake to make here, since the HLSL call order is the reverse of the word order.

Mutation B — the comparison call degrades to a plain sample

-    call = '%s.SampleCmpLevelZero(%s)' % (tex, args)
+    call = '%s.SampleLevel(%s), 0)' % (tex, args)
startup_image_sample_c ........... ***Failed

The comparison itself is asserted, not just "a sample happened".

What this does not say

startup_sampler_comparison stays green under mutation A because it checks the static-sampler mapping, not the call
site; that is consistent with its name, and I mention it so the two fixtures' division of labour is explicit.

The refusal paths (image_sample_c_l needing SM 6.7, c with a non-zero MAX_LOD) I did not drive; they are Unsupported
raises and would need crafted sampler words.

Verdict

Reviewed the current head. Builds clean, all four cases pass across WARP and a physical adapter, and two independent
mutations in the emitted call are caught. No objection from me.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7135619099 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1471#issuecomment-7135619099). Originally posted by [ChazY11](https://github.com/ChazY11) on 2026-11-24T15:11:52Z. --- ## The reference ordering and the comparison call are both covered Independent reviewer, not the author. Reviewed the current head; nothing pushed to the branch. Mutations were made locally in `tools/startup/gfx2hlsl.py`, reverted between each; working tree is clean. Environment: Windows 11 build 26300.9974, MSVC 14.44.35207, SDK 10.0.26100, DXC 1.8.2502.11, LLVM gfx1013 tooling available, RTX 5080 Laptop (32.0.15.8142) for `_hardware`. ```powershell cmake --preset dev cmake --build --preset dev ctest --preset dev --no-tests=error -R 'sample_c|comparison' -V ``` ```text startup_sampler_comparison ....... Passed 0.14 s startup_image_sample_c ........... Passed 0.92 s pixel_aot_comparisons_hardware ... Passed 41.49 s pixel_aot_comparisons_warp ....... Passed 11.56 s ``` ### Mutation A — the address dwords are unpacked in the wrong order The lowering builds `SampleCmpLevelZero(smp, float2(u, v), reference)` from `cs[1]`, `cs[2]` and `cs[0]`. Taking the dwords in file order instead: ```diff - args = '%s, float2(%s, %s), %s' % (smp, self.f(cs[1]), self.f(cs[2]), self.f(cs[0])) + args = '%s, float2(%s, %s), %s' % (smp, self.f(cs[0]), self.f(cs[1]), self.f(cs[2])) ``` ```text startup_image_sample_c ........... ***Failed startup_sampler_comparison ....... Passed ``` So the fixture notices that the reference is the first address dword rather than the first argument slot — which is the easy mistake to make here, since the HLSL call order is the reverse of the word order. ### Mutation B — the comparison call degrades to a plain sample ```diff - call = '%s.SampleCmpLevelZero(%s)' % (tex, args) + call = '%s.SampleLevel(%s), 0)' % (tex, args) ``` ```text startup_image_sample_c ........... ***Failed ``` The comparison itself is asserted, not just "a sample happened". ### What this does not say `startup_sampler_comparison` stays green under mutation A because it checks the static-sampler mapping, not the call site; that is consistent with its name, and I mention it so the two fixtures' division of labour is explicit. The refusal paths (`image_sample_c_l` needing SM 6.7, `c` with a non-zero MAX_LOD) I did not drive; they are `Unsupported` raises and would need crafted sampler words. ### Verdict Reviewed the current head. Builds clean, all four cases pass across WARP and a physical adapter, and two independent mutations in the emitted call are caught. No objection from me.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
R0Y00/Xbox2Windows!1464
No description provided.