shader: split depth-reference views of any sampler table in the SPIR-V bridge #1217

Merged
tedin7 merged 4 commits from upstream-pr/1224 into main 2026-11-24 07:49:11 +00:00
tedin7 commented 2026-11-24 04:22:21 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T04:22:21Z.


Change

split_sampler_views() only handled one hardcoded profile: a variable named %samplers, type IDs %smp and %_ptr_UC_smp, descriptor set 0 binding 1 and OpAccessChain. It now finds every uniform-constant variable whose type is an OpTypeArray or OpTypeRuntimeArray of OpTypeSampler, under any IDs, in any descriptor set except 3, at any binding, reached through OpAccessChain or OpInBoundsAccessChain. The set 3 view keeps the table's binding. Each table is decided on its own: only a table reached by both a depth-reference and an ordinary sample (sparse forms included) gets a view, with several tables each getting one. The set 3 conflict check and the existing refusals are kept. The old "foreign table is refused" case is now a legal comparison-only table and leaves the module unchanged.

Code: tools/spirv_sampler_views.py. Test: tests/spirv_window/sampler.py. Docs: docs/experiments.md. Standalone SPIR-V bridge, no CPU translator touched. AI-assisted.

Verification

Local (Linux, SPIRV-Tools and SPIRV-Cross from apt, no dxc or D3D12):

  • python3 -B tests/spirv_window/sampler.py spirv-as spirv-val spirv-cross exits 0 with this change and exits 1 on origin/main (01b955a9, same test file; the renamed-table and moved-table cases are refused or left unsplit there).
  • compare_sampler.py and check.py with the same three tools: pass.
  • Old and new output are byte-identical on every tests/spirv_window/*.spvasm fixture plus the pixel variant, so no existing bridge input changes.

New cases: renamed IDs with OpInBoundsAccessChain; runtime-sized table at set 2 binding 7 validated by spirv-val, emitted by SPIRV-Cross with the comparison view at register(s7, space3); two split tables plus an ordinary-only and a comparison-only table left alone; sparse ordinary use. Negative controls: set 3 on the table or elsewhere, a bridge_cmp ID, missing or duplicate DescriptorSet/Binding, a decorated table, a non-sampler load type, a non-sampler pointer type, a sampled image that is not an OpSampledImage, two tables sharing one set 3 binding, and an array of images (not a table, module unchanged).

Not run: the GPU readback of the renamed variant (sampler_readback.cpp, unchanged, same four expected words and three descriptor orders as the original; a view wired to the wrong table changes a precise word). Missing prerequisite: a Windows host with dxc and D3D12. The Windows jobs spirv_sampler_views_{hardware,warp} run it.

Evidence and follow-up

Fixtures are the existing synthetic sampler.spvasm edited by the test (renames, type and decoration edits); no game data. Assumption: a table with a sampled image from an unresolvable source counts as possibly used by every table for the ordinary side, so it splits conservatively. Not done: a GPU root signature for a table at a set other than 0 (the readback harness keeps slots 0/1 and 3/1).

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:6574556926 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T04:22:21Z. --- ## Change `split_sampler_views()` only handled one hardcoded profile: a variable named `%samplers`, type IDs `%smp` and `%_ptr_UC_smp`, descriptor set 0 binding 1 and `OpAccessChain`. It now finds every uniform-constant variable whose type is an `OpTypeArray` or `OpTypeRuntimeArray` of `OpTypeSampler`, under any IDs, in any descriptor set except 3, at any binding, reached through `OpAccessChain` or `OpInBoundsAccessChain`. The set 3 view keeps the table's binding. Each table is decided on its own: only a table reached by both a depth-reference and an ordinary sample (sparse forms included) gets a view, with several tables each getting one. The set 3 conflict check and the existing refusals are kept. The old "foreign table is refused" case is now a legal comparison-only table and leaves the module unchanged. Code: `tools/spirv_sampler_views.py`. Test: `tests/spirv_window/sampler.py`. Docs: `docs/experiments.md`. Standalone SPIR-V bridge, no CPU translator touched. AI-assisted. ## Verification Local (Linux, SPIRV-Tools and SPIRV-Cross from apt, no dxc or D3D12): - `python3 -B tests/spirv_window/sampler.py spirv-as spirv-val spirv-cross` exits 0 with this change and exits 1 on origin/main (01b955a9, same test file; the renamed-table and moved-table cases are refused or left unsplit there). - `compare_sampler.py` and `check.py` with the same three tools: pass. - Old and new output are byte-identical on every `tests/spirv_window/*.spvasm` fixture plus the pixel variant, so no existing bridge input changes. New cases: renamed IDs with `OpInBoundsAccessChain`; runtime-sized table at set 2 binding 7 validated by spirv-val, emitted by SPIRV-Cross with the comparison view at `register(s7, space3)`; two split tables plus an ordinary-only and a comparison-only table left alone; sparse ordinary use. Negative controls: set 3 on the table or elsewhere, a `bridge_cmp` ID, missing or duplicate `DescriptorSet`/`Binding`, a decorated table, a non-sampler load type, a non-sampler pointer type, a sampled image that is not an `OpSampledImage`, two tables sharing one set 3 binding, and an array of images (not a table, module unchanged). Not run: the GPU readback of the renamed variant (`sampler_readback.cpp`, unchanged, same four expected words and three descriptor orders as the original; a view wired to the wrong table changes a precise word). Missing prerequisite: a Windows host with dxc and D3D12. The Windows jobs `spirv_sampler_views_{hardware,warp}` run it. ## Evidence and follow-up Fixtures are the existing synthetic `sampler.spvasm` edited by the test (renames, type and decoration edits); no game data. Assumption: a table with a sampled image from an unresolvable source counts as possibly used by every table for the ordinary side, so it splits conservatively. Not done: a GPU root signature for a table at a set other than 0 (the readback harness keeps slots 0/1 and 3/1). ## 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 06:47:04 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T04:32:04Z.

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 771498b470

ℹ️ 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:6033680289 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#pullrequestreview-6033680289). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T04:32:04Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `771498b470` <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 06:47:04 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T04:33:34Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6033690349 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#pullrequestreview-6033690349). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T04:33:34Z. **Review:** COMMENTED --- _No description provided._
tedin7 commented 2026-11-24 06:47:04 +00:00 (Migrated from github.com)

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

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6033690557 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#pullrequestreview-6033690557). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T04:33:36Z. **Review:** COMMENTED --- _No description provided._
chatgpt-codex-connector[bot commented 2026-11-24 06:47:04 +00:00 (Migrated from github.com)

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

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a2f907dd9d

ℹ️ 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:6033736135 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#pullrequestreview-6033736135). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T04:40:24Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `a2f907dd9d` <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 06:47:04 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T04:41:14Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6033741683 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#pullrequestreview-6033741683). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T04:41:14Z. **Review:** COMMENTED --- _No description provided._
chatgpt-codex-connector[bot commented 2026-11-24 06:47:04 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T04:53:28Z.

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 828a072357

ℹ️ 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:6033841078 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#pullrequestreview-6033841078). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T04:53:28Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `828a072357` <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 06:47:04 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T04:54:11Z.

Review: COMMENTED


No description provided.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6033848783 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#pullrequestreview-6033848783). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T04:54:11Z. **Review:** COMMENTED --- _No description provided._
tedin7 commented 2026-11-24 06:50:20 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T04:33:38Z.


Fixed in a2f907dd: split tables now refuse overlapping set 3 register ranges (fixed size, runtime size and equal bindings, with tests), and a ; comment after any declaration no longer hides the sampler types (the test adds comments and a semicolon inside a quoted name). tests/spirv_window/sampler.py fails on the previous commit and passes now.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7122130428 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#issuecomment-7122130428). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T04:33:38Z. --- Fixed in a2f907dd: split tables now refuse overlapping set 3 register ranges (fixed size, runtime size and equal bindings, with tests), and a ; comment after any declaration no longer hides the sampler types (the test adds comments and a semicolon inside a quoted name). tests/spirv_window/sampler.py fails on the previous commit and passes now.
tedin7 commented 2026-11-24 06:50:20 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T04:34:03Z.


AI-assisted update: both P2 findings are fixed in a2f907dd (overlapping set 3 register ranges are refused; ; comments are stripped before matching). Local checks: tests/spirv_window/sampler.py and check.py pass; sampler.py fails on the previous commit.

@codex review

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7122136788 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#issuecomment-7122136788). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T04:34:03Z. --- AI-assisted update: both P2 findings are fixed in a2f907dd (overlapping set 3 register ranges are refused; ; comments are stripped before matching). Local checks: tests/spirv_window/sampler.py and check.py pass; sampler.py fails on the previous commit. @codex review
tedin7 commented 2026-11-24 06:50:21 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T04:41:16Z.


Fixed in 828a0723: the reserved set 3 check now reads the parsed DescriptorSet decorations (extra whitespace, tabs and leading zeros included); test added, fails on the previous commit.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7122246555 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#issuecomment-7122246555). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T04:41:16Z. --- Fixed in 828a0723: the reserved set 3 check now reads the parsed DescriptorSet decorations (extra whitespace, tabs and leading zeros included); test added, fails on the previous commit.
tedin7 commented 2026-11-24 06:50:21 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T04:44:20Z.


AI-assisted: the third P2 is fixed in 828a0723, sampler.py and check.py pass locally.

@codex review

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7122292595 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#issuecomment-7122292595). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T04:44:20Z. --- AI-assisted: the third P2 is fixed in 828a0723, sampler.py and check.py pass locally. @codex review
tedin7 commented 2026-11-24 06:50:22 +00:00 (Migrated from github.com)

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


Fixed in 0806ef57: comment stripping now carries quote and escape state across the whole assembly, so a multiline string with a semicolon on a continuation line is kept intact (test assembles and validates it; it fails on the previous commit).

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7122442188 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#issuecomment-7122442188). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T04:54:13Z. --- Fixed in 0806ef57: comment stripping now carries quote and escape state across the whole assembly, so a multiline string with a semicolon on a continuation line is kept intact (test assembles and validates it; it fails on the previous commit).
tedin7 commented 2026-11-24 06:50:23 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T04:57:22Z.


Windows Server 2025 verification (0806ef57) — PASS (Debug + Release /O2, WARP)

  • Environment: Windows Server 2025 Build 26100, MSVC 14.44.35207, AMD Ryzen 5 PRO 5650U, D3D12 WARP
  • Debug (--preset dev) (11.54s build+test):
    • cmake --build --preset dev -j 6 --target offscreen_check
    • ctest --test-dir out\build\dev -R "^spirv_.*_warp$" --output-on-failure -> 11/11 passed (0 skipped, 11.41s; spirv_sampler_views_warp 0.88s)
  • Release /O2 (--preset release) (12.29s configure+build+test):
    • cmake --preset release && cmake --build --preset release -j 6 --target offscreen_check
    • ctest --test-dir out\build\release -R "^spirv_.*_warp$" --output-on-failure -> 11/11 passed (0 skipped, 10.55s; spirv_sampler_views_warp 0.68s)
<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7122490233 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#issuecomment-7122490233). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T04:57:22Z. --- Windows Server 2025 verification (`0806ef57`) — **PASS (Debug + Release `/O2`, WARP)** - **Environment**: Windows Server 2025 Build 26100, MSVC 14.44.35207, AMD Ryzen 5 PRO 5650U, D3D12 WARP - **Debug (`--preset dev`)** (11.54s build+test): - `cmake --build --preset dev -j 6 --target offscreen_check` - `ctest --test-dir out\build\dev -R "^spirv_.*_warp$" --output-on-failure` -> **11/11 passed** (0 skipped, 11.41s; `spirv_sampler_views_warp` 0.88s) - **Release `/O2` (`--preset release`)** (12.29s configure+build+test): - `cmake --preset release && cmake --build --preset release -j 6 --target offscreen_check` - `ctest --test-dir out\build\release -R "^spirv_.*_warp$" --output-on-failure` -> **11/11 passed** (0 skipped, 10.55s; `spirv_sampler_views_warp` 0.68s)
tedin7 commented 2026-11-24 06:50:23 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T05:02:15Z.


@codex review

AI-assisted: all inline findings are fixed through 0806ef57; please re-read the current head.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7122564152 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#issuecomment-7122564152). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T05:02:15Z. --- @codex review AI-assisted: all inline findings are fixed through 0806ef57; please re-read the current head.
chatgpt-codex-connector[bot commented 2026-11-24 06:50:25 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T05:12:05Z.


Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 0806ef5769

ℹ️ 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:comment:7122719883 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#issuecomment-7122719883). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T05:12:05Z. --- <!-- codex-review-receipt:v1 --> Codex Review: Didn't find any major issues. Delightful! **Reviewed commit:** `0806ef5769` <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>
chatgpt-codex-connector[bot commented 2026-11-24 06:50:25 +00:00 (Migrated from github.com)

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


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-24T05:12:06.158171Z 0806ef5 Manual request
ℹ️ 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:7121995531 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#issuecomment-7121995531). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T04:24:49Z. --- <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"0806ef576983d3dc233b3ba6ee97967ed91e8e2f","has_any_findings":false,"has_unresolved_findings":false,"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-24T05:12:06.158171Z">2026-11-24T05:12:06.158171Z</relative-time> | `0806ef5` | Manual request | <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 06:50:40 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T04:32:04Z.

Code review location: tools/spirv_sampler_views.py; line 127

@@ -1,71 +1,177 @@
-"""Separate the named bindless sampler table's depth-reference uses for HLSL."""
+"""Separate the depth-reference uses of a bindless sampler table for HLSL.
+
+SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and
+depth-reference samples needs a second view. This pass finds every uniform-constant variable whose
+type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a
+copy of it at descriptor set 3 and the same binding for the depth-reference uses.
+"""
 import re
 
+CHAINS = ("OpAccessChain", "OpInBoundsAccessChain")
+BRIDGE = "%bridge_cmp"
+BRIDGE_SET = "3"
 
-def split_sampler_views(assembly):
-    if "Dref" not in assembly or "%samplers " not in assembly:
-        return assembly
-    lines = assembly.splitlines()
-    definitions = {}
-    comparisons = []
-    ordinary = False
-    decorated = set()
-    indirect_decorations = False
+
+def read_module(lines):
+    """Collect result definitions, sample instructions and decorations from the assembly lines."""
+    module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False,
+              "sets": {}, "bindings": {}}
     for index, line in enumerate(lines):
         words = line.split()
         if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]):
-            indirect_decorations = True
-        if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"):
-            decorated.add(words[1])
-        if len(words) < 4 or words[1] != "=":
+            module["indirect"] = True
+        if words[:1] == ["OpDecorate"] and len(words) >= 3:
+            if words[2] == "DescriptorSet":
+                module["sets"].setdefault(words[1], []).append(words[3:])
+            elif words[2] == "Binding":
+                module["bindings"].setdefault(words[1], []).append(words[3:])
+            else:
+                module["decorated"].add(words[1])
+        if len(words) < 3 or words[1] != "=":
             continue
-        definitions[words[0]] = words[2:]
+        module["defs"][words[0]] = words[2:]
         if words[2].startswith("OpImage") and "Dref" in words[2]:
-            comparisons.append((index, words))
-        elif words[2].startswith(("OpImageSample", "OpImageGather")):
-            ordinary = True
-    if not comparisons or not ordinary:
+            module["comparisons"].append((index, words))
+        elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")):
+            module["ordinary"].append(words)
+    return module
+
+
+def pointee(defs, variable):
+    """The type a uniform-constant variable points to, or None."""
+    declaration = defs.get(variable, [])
+    if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant":
+        return None
+    pointer = defs.get(declaration[1], [])
+    if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]:
+        return None
+    return pointer[2]
+
+
+def sampler_variables(defs):
+    """Return the sampler tables and the plain sampler variables, in declaration order."""
+    tables, plains = [], set()
+    for name in defs:
+        target = pointee(defs, name)
+        if target is None:
+            continue
+        shape = defs.get(target, [])
+        if shape == ["OpTypeSampler"]:
+            plains.add(name)
+        elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]:
+            tables.append(name)
+    return tables, plains
+
+
+def sampler_source(defs, tables, plains, sampled):
+    """Follow a sampled image to its sampler: ("table", chain, load, image) or (kind, ...) otherwise."""
+    image = defs.get(sampled, [])
+    if len(image) != 4 or image[0] != "OpSampledImage":
+        return ("image",)
+    load = defs.get(image[3], [])
+    if len(load) != 3 or load[0] != "OpLoad" or defs.get(load[1]) != ["OpTypeSampler"]:
+        return ("load",)
+    if load[2] in plains:
+        return ("plain",)
+    chain = defs.get(load[2], [])
+    if (len(chain) == 4 and chain[0] in CHAINS and chain[2] in tables
+            and defs.get(chain[1]) == ["OpTypePointer", "UniformConstant", load[1]]):
+        return ("table", chain, load, image, image[3], load[2])
+    return ("provenance",)
+
+
+FAILURES = {"image": "unsupported depth-reference sampled image",
+            "load": "unsupported depth-reference sampler load",
+            "provenance": "unsupported depth-reference sampler provenance"}
+
+
+def tables_to_split(module, tables, plains):
+    """Tables used by a depth-reference sample and by an ordinary one; also the resolved comparisons."""
+    defs = module["defs"]
+    ordinary, unresolved = set(), False
+    for words in module["ordinary"]:
+        source = sampler_source(defs, tables, plains, words[4])
+        if source[0] == "table":
+            ordinary.add(source[1][2])
+        elif source[0] != "plain":
+            unresolved = True  # an ordinary sample with an unknown sampler may use any table
+    resolved = []
+    for index, words in module["comparisons"]:
+        source = sampler_source(defs, tables, plains, words[4])
+        if source[0] == "table":
+            resolved.append((index, words, source))
+        elif source[0] != "plain":
+            raise ValueError(FAILURES[source[0]])
+    return resolved, ordinary, unresolved
+
+
+def table_slot(module, table):
+    """The (set, binding) of a table; it must carry exactly one of each and no other decoration."""
+    sets, bindings = module["sets"].get(table, []), module["bindings"].get(table, [])
+    if len(sets) != 1 or len(bindings) != 1 or len(sets[0]) != 1 or len(bindings[0]) != 1:
+        raise ValueError("sampler table requires one DescriptorSet and one Binding decoration")
+    if not (sets[0][0].isdigit() and bindings[0][0].isdigit()):
+        raise ValueError("sampler table requires literal DescriptorSet and Binding numbers")
+    if table in module["decorated"] or len(module["defs"][table]) != 3:
+        raise ValueError("unsupported sampler table declaration")
+    return sets[0][0], bindings[0][0]
+
+
+def bridge_names(module, split):
+    """Name one bridge variable per split table; the first keeps the plain prefix."""
+    names, used = {}, {}
+    for number, table in enumerate(split):
+        _, binding = table_slot(module, table)
+        if binding in used:
+            raise ValueError("sampler tables share binding " + binding + ": " + used[binding] + " and " + table)
+        used[binding] = table

P2 Badge Reject overlapping register ranges, not just equal bindings

For two mixed two-element tables at (set 0, binding 1) and (set 2, binding 2), this check accepts both and moves their comparison arrays to bindings 1 and 2 in set 3. The corresponding HLSL arrays occupy s1..s2 and s2..s3 in space3, so the comparison views overlap at s2 even though the original tables were in separate spaces. The two views therefore cannot bind their descriptors independently; multiple runtime-sized tables have the same problem. Check the full register ranges, or refuse overlapping layouts, before emitting the views.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675542333 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#discussion_r4675542333). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T04:32:04Z. **Code review location:** `tools/spirv_sampler_views.py`; line 127 ~~~~diff @@ -1,71 +1,177 @@ -"""Separate the named bindless sampler table's depth-reference uses for HLSL.""" +"""Separate the depth-reference uses of a bindless sampler table for HLSL. + +SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and +depth-reference samples needs a second view. This pass finds every uniform-constant variable whose +type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a +copy of it at descriptor set 3 and the same binding for the depth-reference uses. +""" import re +CHAINS = ("OpAccessChain", "OpInBoundsAccessChain") +BRIDGE = "%bridge_cmp" +BRIDGE_SET = "3" -def split_sampler_views(assembly): - if "Dref" not in assembly or "%samplers " not in assembly: - return assembly - lines = assembly.splitlines() - definitions = {} - comparisons = [] - ordinary = False - decorated = set() - indirect_decorations = False + +def read_module(lines): + """Collect result definitions, sample instructions and decorations from the assembly lines.""" + module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False, + "sets": {}, "bindings": {}} for index, line in enumerate(lines): words = line.split() if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]): - indirect_decorations = True - if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"): - decorated.add(words[1]) - if len(words) < 4 or words[1] != "=": + module["indirect"] = True + if words[:1] == ["OpDecorate"] and len(words) >= 3: + if words[2] == "DescriptorSet": + module["sets"].setdefault(words[1], []).append(words[3:]) + elif words[2] == "Binding": + module["bindings"].setdefault(words[1], []).append(words[3:]) + else: + module["decorated"].add(words[1]) + if len(words) < 3 or words[1] != "=": continue - definitions[words[0]] = words[2:] + module["defs"][words[0]] = words[2:] if words[2].startswith("OpImage") and "Dref" in words[2]: - comparisons.append((index, words)) - elif words[2].startswith(("OpImageSample", "OpImageGather")): - ordinary = True - if not comparisons or not ordinary: + module["comparisons"].append((index, words)) + elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")): + module["ordinary"].append(words) + return module + + +def pointee(defs, variable): + """The type a uniform-constant variable points to, or None.""" + declaration = defs.get(variable, []) + if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant": + return None + pointer = defs.get(declaration[1], []) + if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]: + return None + return pointer[2] + + +def sampler_variables(defs): + """Return the sampler tables and the plain sampler variables, in declaration order.""" + tables, plains = [], set() + for name in defs: + target = pointee(defs, name) + if target is None: + continue + shape = defs.get(target, []) + if shape == ["OpTypeSampler"]: + plains.add(name) + elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]: + tables.append(name) + return tables, plains + + +def sampler_source(defs, tables, plains, sampled): + """Follow a sampled image to its sampler: ("table", chain, load, image) or (kind, ...) otherwise.""" + image = defs.get(sampled, []) + if len(image) != 4 or image[0] != "OpSampledImage": + return ("image",) + load = defs.get(image[3], []) + if len(load) != 3 or load[0] != "OpLoad" or defs.get(load[1]) != ["OpTypeSampler"]: + return ("load",) + if load[2] in plains: + return ("plain",) + chain = defs.get(load[2], []) + if (len(chain) == 4 and chain[0] in CHAINS and chain[2] in tables + and defs.get(chain[1]) == ["OpTypePointer", "UniformConstant", load[1]]): + return ("table", chain, load, image, image[3], load[2]) + return ("provenance",) + + +FAILURES = {"image": "unsupported depth-reference sampled image", + "load": "unsupported depth-reference sampler load", + "provenance": "unsupported depth-reference sampler provenance"} + + +def tables_to_split(module, tables, plains): + """Tables used by a depth-reference sample and by an ordinary one; also the resolved comparisons.""" + defs = module["defs"] + ordinary, unresolved = set(), False + for words in module["ordinary"]: + source = sampler_source(defs, tables, plains, words[4]) + if source[0] == "table": + ordinary.add(source[1][2]) + elif source[0] != "plain": + unresolved = True # an ordinary sample with an unknown sampler may use any table + resolved = [] + for index, words in module["comparisons"]: + source = sampler_source(defs, tables, plains, words[4]) + if source[0] == "table": + resolved.append((index, words, source)) + elif source[0] != "plain": + raise ValueError(FAILURES[source[0]]) + return resolved, ordinary, unresolved + + +def table_slot(module, table): + """The (set, binding) of a table; it must carry exactly one of each and no other decoration.""" + sets, bindings = module["sets"].get(table, []), module["bindings"].get(table, []) + if len(sets) != 1 or len(bindings) != 1 or len(sets[0]) != 1 or len(bindings[0]) != 1: + raise ValueError("sampler table requires one DescriptorSet and one Binding decoration") + if not (sets[0][0].isdigit() and bindings[0][0].isdigit()): + raise ValueError("sampler table requires literal DescriptorSet and Binding numbers") + if table in module["decorated"] or len(module["defs"][table]) != 3: + raise ValueError("unsupported sampler table declaration") + return sets[0][0], bindings[0][0] + + +def bridge_names(module, split): + """Name one bridge variable per split table; the first keeps the plain prefix.""" + names, used = {}, {} + for number, table in enumerate(split): + _, binding = table_slot(module, table) + if binding in used: + raise ValueError("sampler tables share binding " + binding + ": " + used[binding] + " and " + table) + used[binding] = table ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Reject overlapping register ranges, not just equal bindings** For two mixed two-element tables at `(set 0, binding 1)` and `(set 2, binding 2)`, this check accepts both and moves their comparison arrays to bindings 1 and 2 in set 3. The corresponding HLSL arrays occupy `s1..s2` and `s2..s3` in `space3`, so the comparison views overlap at `s2` even though the original tables were in separate spaces. The two views therefore cannot bind their descriptors independently; multiple runtime-sized tables have the same problem. Check the full register ranges, or refuse overlapping layouts, before emitting the views. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot commented 2026-11-24 06:50:41 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T04:32:04Z.

Code review location: tools/spirv_sampler_views.py; line 61

@@ -1,71 +1,177 @@
-"""Separate the named bindless sampler table's depth-reference uses for HLSL."""
+"""Separate the depth-reference uses of a bindless sampler table for HLSL.
+
+SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and
+depth-reference samples needs a second view. This pass finds every uniform-constant variable whose
+type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a
+copy of it at descriptor set 3 and the same binding for the depth-reference uses.
+"""
 import re
 
+CHAINS = ("OpAccessChain", "OpInBoundsAccessChain")
+BRIDGE = "%bridge_cmp"
+BRIDGE_SET = "3"
 
-def split_sampler_views(assembly):
-    if "Dref" not in assembly or "%samplers " not in assembly:
-        return assembly
-    lines = assembly.splitlines()
-    definitions = {}
-    comparisons = []
-    ordinary = False
-    decorated = set()
-    indirect_decorations = False
+
+def read_module(lines):
+    """Collect result definitions, sample instructions and decorations from the assembly lines."""
+    module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False,
+              "sets": {}, "bindings": {}}
     for index, line in enumerate(lines):
         words = line.split()
         if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]):
-            indirect_decorations = True
-        if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"):
-            decorated.add(words[1])
-        if len(words) < 4 or words[1] != "=":
+            module["indirect"] = True
+        if words[:1] == ["OpDecorate"] and len(words) >= 3:
+            if words[2] == "DescriptorSet":
+                module["sets"].setdefault(words[1], []).append(words[3:])
+            elif words[2] == "Binding":
+                module["bindings"].setdefault(words[1], []).append(words[3:])
+            else:
+                module["decorated"].add(words[1])
+        if len(words) < 3 or words[1] != "=":
             continue
-        definitions[words[0]] = words[2:]
+        module["defs"][words[0]] = words[2:]
         if words[2].startswith("OpImage") and "Dref" in words[2]:
-            comparisons.append((index, words))
-        elif words[2].startswith(("OpImageSample", "OpImageGather")):
-            ordinary = True
-    if not comparisons or not ordinary:
+            module["comparisons"].append((index, words))
+        elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")):
+            module["ordinary"].append(words)
+    return module
+
+
+def pointee(defs, variable):
+    """The type a uniform-constant variable points to, or None."""
+    declaration = defs.get(variable, [])
+    if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant":
+        return None
+    pointer = defs.get(declaration[1], [])
+    if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]:
+        return None
+    return pointer[2]
+
+
+def sampler_variables(defs):
+    """Return the sampler tables and the plain sampler variables, in declaration order."""
+    tables, plains = [], set()
+    for name in defs:
+        target = pointee(defs, name)
+        if target is None:
+            continue
+        shape = defs.get(target, [])
+        if shape == ["OpTypeSampler"]:
+            plains.add(name)
+        elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]:

P2 Badge Strip inline comments before matching sampler types

Adding a valid inline comment such as %smp = OpTypeSampler ; sampler type to the existing fixture makes read_module() include the comment tokens in the stored definition, so this equality no longer recognizes the sampler table. split_sampler_views() then silently returns the original mixed module, leaving ordinary and depth-reference operations on the same sampler and recreating the HLSL type conflict. The parent commit still splits this same input. Strip or tokenize SPIR-V comments before matching type declarations.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675542343 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#discussion_r4675542343). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T04:32:04Z. **Code review location:** `tools/spirv_sampler_views.py`; line 61 ~~~~diff @@ -1,71 +1,177 @@ -"""Separate the named bindless sampler table's depth-reference uses for HLSL.""" +"""Separate the depth-reference uses of a bindless sampler table for HLSL. + +SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and +depth-reference samples needs a second view. This pass finds every uniform-constant variable whose +type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a +copy of it at descriptor set 3 and the same binding for the depth-reference uses. +""" import re +CHAINS = ("OpAccessChain", "OpInBoundsAccessChain") +BRIDGE = "%bridge_cmp" +BRIDGE_SET = "3" -def split_sampler_views(assembly): - if "Dref" not in assembly or "%samplers " not in assembly: - return assembly - lines = assembly.splitlines() - definitions = {} - comparisons = [] - ordinary = False - decorated = set() - indirect_decorations = False + +def read_module(lines): + """Collect result definitions, sample instructions and decorations from the assembly lines.""" + module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False, + "sets": {}, "bindings": {}} for index, line in enumerate(lines): words = line.split() if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]): - indirect_decorations = True - if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"): - decorated.add(words[1]) - if len(words) < 4 or words[1] != "=": + module["indirect"] = True + if words[:1] == ["OpDecorate"] and len(words) >= 3: + if words[2] == "DescriptorSet": + module["sets"].setdefault(words[1], []).append(words[3:]) + elif words[2] == "Binding": + module["bindings"].setdefault(words[1], []).append(words[3:]) + else: + module["decorated"].add(words[1]) + if len(words) < 3 or words[1] != "=": continue - definitions[words[0]] = words[2:] + module["defs"][words[0]] = words[2:] if words[2].startswith("OpImage") and "Dref" in words[2]: - comparisons.append((index, words)) - elif words[2].startswith(("OpImageSample", "OpImageGather")): - ordinary = True - if not comparisons or not ordinary: + module["comparisons"].append((index, words)) + elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")): + module["ordinary"].append(words) + return module + + +def pointee(defs, variable): + """The type a uniform-constant variable points to, or None.""" + declaration = defs.get(variable, []) + if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant": + return None + pointer = defs.get(declaration[1], []) + if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]: + return None + return pointer[2] + + +def sampler_variables(defs): + """Return the sampler tables and the plain sampler variables, in declaration order.""" + tables, plains = [], set() + for name in defs: + target = pointee(defs, name) + if target is None: + continue + shape = defs.get(target, []) + if shape == ["OpTypeSampler"]: + plains.add(name) + elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]: ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Strip inline comments before matching sampler types** Adding a valid inline comment such as `%smp = OpTypeSampler ; sampler type` to the existing fixture makes `read_module()` include the comment tokens in the stored definition, so this equality no longer recognizes the sampler table. `split_sampler_views()` then silently returns the original mixed module, leaving ordinary and depth-reference operations on the same sampler and recreating the HLSL type conflict. The parent commit still splits this same input. Strip or tokenize SPIR-V comments before matching type declarations. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
tedin7 commented 2026-11-24 06:50:41 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T04:33:34Z.

Code review location: tools/spirv_sampler_views.py; line 127

@@ -1,71 +1,177 @@
-"""Separate the named bindless sampler table's depth-reference uses for HLSL."""
+"""Separate the depth-reference uses of a bindless sampler table for HLSL.
+
+SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and
+depth-reference samples needs a second view. This pass finds every uniform-constant variable whose
+type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a
+copy of it at descriptor set 3 and the same binding for the depth-reference uses.
+"""
 import re
 
+CHAINS = ("OpAccessChain", "OpInBoundsAccessChain")
+BRIDGE = "%bridge_cmp"
+BRIDGE_SET = "3"
 
-def split_sampler_views(assembly):
-    if "Dref" not in assembly or "%samplers " not in assembly:
-        return assembly
-    lines = assembly.splitlines()
-    definitions = {}
-    comparisons = []
-    ordinary = False
-    decorated = set()
-    indirect_decorations = False
+
+def read_module(lines):
+    """Collect result definitions, sample instructions and decorations from the assembly lines."""
+    module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False,
+              "sets": {}, "bindings": {}}
     for index, line in enumerate(lines):
         words = line.split()
         if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]):
-            indirect_decorations = True
-        if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"):
-            decorated.add(words[1])
-        if len(words) < 4 or words[1] != "=":
+            module["indirect"] = True
+        if words[:1] == ["OpDecorate"] and len(words) >= 3:
+            if words[2] == "DescriptorSet":
+                module["sets"].setdefault(words[1], []).append(words[3:])
+            elif words[2] == "Binding":
+                module["bindings"].setdefault(words[1], []).append(words[3:])
+            else:
+                module["decorated"].add(words[1])
+        if len(words) < 3 or words[1] != "=":
             continue
-        definitions[words[0]] = words[2:]
+        module["defs"][words[0]] = words[2:]
         if words[2].startswith("OpImage") and "Dref" in words[2]:
-            comparisons.append((index, words))
-        elif words[2].startswith(("OpImageSample", "OpImageGather")):
-            ordinary = True
-    if not comparisons or not ordinary:
+            module["comparisons"].append((index, words))
+        elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")):
+            module["ordinary"].append(words)
+    return module
+
+
+def pointee(defs, variable):
+    """The type a uniform-constant variable points to, or None."""
+    declaration = defs.get(variable, [])
+    if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant":
+        return None
+    pointer = defs.get(declaration[1], [])
+    if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]:
+        return None
+    return pointer[2]
+
+
+def sampler_variables(defs):
+    """Return the sampler tables and the plain sampler variables, in declaration order."""
+    tables, plains = [], set()
+    for name in defs:
+        target = pointee(defs, name)
+        if target is None:
+            continue
+        shape = defs.get(target, [])
+        if shape == ["OpTypeSampler"]:
+            plains.add(name)
+        elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]:
+            tables.append(name)
+    return tables, plains
+
+
+def sampler_source(defs, tables, plains, sampled):
+    """Follow a sampled image to its sampler: ("table", chain, load, image) or (kind, ...) otherwise."""
+    image = defs.get(sampled, [])
+    if len(image) != 4 or image[0] != "OpSampledImage":
+        return ("image",)
+    load = defs.get(image[3], [])
+    if len(load) != 3 or load[0] != "OpLoad" or defs.get(load[1]) != ["OpTypeSampler"]:
+        return ("load",)
+    if load[2] in plains:
+        return ("plain",)
+    chain = defs.get(load[2], [])
+    if (len(chain) == 4 and chain[0] in CHAINS and chain[2] in tables
+            and defs.get(chain[1]) == ["OpTypePointer", "UniformConstant", load[1]]):
+        return ("table", chain, load, image, image[3], load[2])
+    return ("provenance",)
+
+
+FAILURES = {"image": "unsupported depth-reference sampled image",
+            "load": "unsupported depth-reference sampler load",
+            "provenance": "unsupported depth-reference sampler provenance"}
+
+
+def tables_to_split(module, tables, plains):
+    """Tables used by a depth-reference sample and by an ordinary one; also the resolved comparisons."""
+    defs = module["defs"]
+    ordinary, unresolved = set(), False
+    for words in module["ordinary"]:
+        source = sampler_source(defs, tables, plains, words[4])
+        if source[0] == "table":
+            ordinary.add(source[1][2])
+        elif source[0] != "plain":
+            unresolved = True  # an ordinary sample with an unknown sampler may use any table
+    resolved = []
+    for index, words in module["comparisons"]:
+        source = sampler_source(defs, tables, plains, words[4])
+        if source[0] == "table":
+            resolved.append((index, words, source))
+        elif source[0] != "plain":
+            raise ValueError(FAILURES[source[0]])
+    return resolved, ordinary, unresolved
+
+
+def table_slot(module, table):
+    """The (set, binding) of a table; it must carry exactly one of each and no other decoration."""
+    sets, bindings = module["sets"].get(table, []), module["bindings"].get(table, [])
+    if len(sets) != 1 or len(bindings) != 1 or len(sets[0]) != 1 or len(bindings[0]) != 1:
+        raise ValueError("sampler table requires one DescriptorSet and one Binding decoration")
+    if not (sets[0][0].isdigit() and bindings[0][0].isdigit()):
+        raise ValueError("sampler table requires literal DescriptorSet and Binding numbers")
+    if table in module["decorated"] or len(module["defs"][table]) != 3:
+        raise ValueError("unsupported sampler table declaration")
+    return sets[0][0], bindings[0][0]
+
+
+def bridge_names(module, split):
+    """Name one bridge variable per split table; the first keeps the plain prefix."""
+    names, used = {}, {}
+    for number, table in enumerate(split):
+        _, binding = table_slot(module, table)
+        if binding in used:
+            raise ValueError("sampler tables share binding " + binding + ": " + used[binding] + " and " + table)
+        used[binding] = table

Fixed in a2f907dd

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675551074 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#discussion_r4675551074). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T04:33:34Z. **Code review location:** `tools/spirv_sampler_views.py`; line 127 ~~~~diff @@ -1,71 +1,177 @@ -"""Separate the named bindless sampler table's depth-reference uses for HLSL.""" +"""Separate the depth-reference uses of a bindless sampler table for HLSL. + +SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and +depth-reference samples needs a second view. This pass finds every uniform-constant variable whose +type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a +copy of it at descriptor set 3 and the same binding for the depth-reference uses. +""" import re +CHAINS = ("OpAccessChain", "OpInBoundsAccessChain") +BRIDGE = "%bridge_cmp" +BRIDGE_SET = "3" -def split_sampler_views(assembly): - if "Dref" not in assembly or "%samplers " not in assembly: - return assembly - lines = assembly.splitlines() - definitions = {} - comparisons = [] - ordinary = False - decorated = set() - indirect_decorations = False + +def read_module(lines): + """Collect result definitions, sample instructions and decorations from the assembly lines.""" + module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False, + "sets": {}, "bindings": {}} for index, line in enumerate(lines): words = line.split() if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]): - indirect_decorations = True - if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"): - decorated.add(words[1]) - if len(words) < 4 or words[1] != "=": + module["indirect"] = True + if words[:1] == ["OpDecorate"] and len(words) >= 3: + if words[2] == "DescriptorSet": + module["sets"].setdefault(words[1], []).append(words[3:]) + elif words[2] == "Binding": + module["bindings"].setdefault(words[1], []).append(words[3:]) + else: + module["decorated"].add(words[1]) + if len(words) < 3 or words[1] != "=": continue - definitions[words[0]] = words[2:] + module["defs"][words[0]] = words[2:] if words[2].startswith("OpImage") and "Dref" in words[2]: - comparisons.append((index, words)) - elif words[2].startswith(("OpImageSample", "OpImageGather")): - ordinary = True - if not comparisons or not ordinary: + module["comparisons"].append((index, words)) + elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")): + module["ordinary"].append(words) + return module + + +def pointee(defs, variable): + """The type a uniform-constant variable points to, or None.""" + declaration = defs.get(variable, []) + if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant": + return None + pointer = defs.get(declaration[1], []) + if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]: + return None + return pointer[2] + + +def sampler_variables(defs): + """Return the sampler tables and the plain sampler variables, in declaration order.""" + tables, plains = [], set() + for name in defs: + target = pointee(defs, name) + if target is None: + continue + shape = defs.get(target, []) + if shape == ["OpTypeSampler"]: + plains.add(name) + elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]: + tables.append(name) + return tables, plains + + +def sampler_source(defs, tables, plains, sampled): + """Follow a sampled image to its sampler: ("table", chain, load, image) or (kind, ...) otherwise.""" + image = defs.get(sampled, []) + if len(image) != 4 or image[0] != "OpSampledImage": + return ("image",) + load = defs.get(image[3], []) + if len(load) != 3 or load[0] != "OpLoad" or defs.get(load[1]) != ["OpTypeSampler"]: + return ("load",) + if load[2] in plains: + return ("plain",) + chain = defs.get(load[2], []) + if (len(chain) == 4 and chain[0] in CHAINS and chain[2] in tables + and defs.get(chain[1]) == ["OpTypePointer", "UniformConstant", load[1]]): + return ("table", chain, load, image, image[3], load[2]) + return ("provenance",) + + +FAILURES = {"image": "unsupported depth-reference sampled image", + "load": "unsupported depth-reference sampler load", + "provenance": "unsupported depth-reference sampler provenance"} + + +def tables_to_split(module, tables, plains): + """Tables used by a depth-reference sample and by an ordinary one; also the resolved comparisons.""" + defs = module["defs"] + ordinary, unresolved = set(), False + for words in module["ordinary"]: + source = sampler_source(defs, tables, plains, words[4]) + if source[0] == "table": + ordinary.add(source[1][2]) + elif source[0] != "plain": + unresolved = True # an ordinary sample with an unknown sampler may use any table + resolved = [] + for index, words in module["comparisons"]: + source = sampler_source(defs, tables, plains, words[4]) + if source[0] == "table": + resolved.append((index, words, source)) + elif source[0] != "plain": + raise ValueError(FAILURES[source[0]]) + return resolved, ordinary, unresolved + + +def table_slot(module, table): + """The (set, binding) of a table; it must carry exactly one of each and no other decoration.""" + sets, bindings = module["sets"].get(table, []), module["bindings"].get(table, []) + if len(sets) != 1 or len(bindings) != 1 or len(sets[0]) != 1 or len(bindings[0]) != 1: + raise ValueError("sampler table requires one DescriptorSet and one Binding decoration") + if not (sets[0][0].isdigit() and bindings[0][0].isdigit()): + raise ValueError("sampler table requires literal DescriptorSet and Binding numbers") + if table in module["decorated"] or len(module["defs"][table]) != 3: + raise ValueError("unsupported sampler table declaration") + return sets[0][0], bindings[0][0] + + +def bridge_names(module, split): + """Name one bridge variable per split table; the first keeps the plain prefix.""" + names, used = {}, {} + for number, table in enumerate(split): + _, binding = table_slot(module, table) + if binding in used: + raise ValueError("sampler tables share binding " + binding + ": " + used[binding] + " and " + table) + used[binding] = table ~~~~ --- Fixed in a2f907dd
tedin7 commented 2026-11-24 06:50:41 +00:00 (Migrated from github.com)

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

Code review location: tools/spirv_sampler_views.py; line 61

@@ -1,71 +1,177 @@
-"""Separate the named bindless sampler table's depth-reference uses for HLSL."""
+"""Separate the depth-reference uses of a bindless sampler table for HLSL.
+
+SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and
+depth-reference samples needs a second view. This pass finds every uniform-constant variable whose
+type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a
+copy of it at descriptor set 3 and the same binding for the depth-reference uses.
+"""
 import re
 
+CHAINS = ("OpAccessChain", "OpInBoundsAccessChain")
+BRIDGE = "%bridge_cmp"
+BRIDGE_SET = "3"
 
-def split_sampler_views(assembly):
-    if "Dref" not in assembly or "%samplers " not in assembly:
-        return assembly
-    lines = assembly.splitlines()
-    definitions = {}
-    comparisons = []
-    ordinary = False
-    decorated = set()
-    indirect_decorations = False
+
+def read_module(lines):
+    """Collect result definitions, sample instructions and decorations from the assembly lines."""
+    module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False,
+              "sets": {}, "bindings": {}}
     for index, line in enumerate(lines):
         words = line.split()
         if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]):
-            indirect_decorations = True
-        if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"):
-            decorated.add(words[1])
-        if len(words) < 4 or words[1] != "=":
+            module["indirect"] = True
+        if words[:1] == ["OpDecorate"] and len(words) >= 3:
+            if words[2] == "DescriptorSet":
+                module["sets"].setdefault(words[1], []).append(words[3:])
+            elif words[2] == "Binding":
+                module["bindings"].setdefault(words[1], []).append(words[3:])
+            else:
+                module["decorated"].add(words[1])
+        if len(words) < 3 or words[1] != "=":
             continue
-        definitions[words[0]] = words[2:]
+        module["defs"][words[0]] = words[2:]
         if words[2].startswith("OpImage") and "Dref" in words[2]:
-            comparisons.append((index, words))
-        elif words[2].startswith(("OpImageSample", "OpImageGather")):
-            ordinary = True
-    if not comparisons or not ordinary:
+            module["comparisons"].append((index, words))
+        elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")):
+            module["ordinary"].append(words)
+    return module
+
+
+def pointee(defs, variable):
+    """The type a uniform-constant variable points to, or None."""
+    declaration = defs.get(variable, [])
+    if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant":
+        return None
+    pointer = defs.get(declaration[1], [])
+    if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]:
+        return None
+    return pointer[2]
+
+
+def sampler_variables(defs):
+    """Return the sampler tables and the plain sampler variables, in declaration order."""
+    tables, plains = [], set()
+    for name in defs:
+        target = pointee(defs, name)
+        if target is None:
+            continue
+        shape = defs.get(target, [])
+        if shape == ["OpTypeSampler"]:
+            plains.add(name)
+        elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]:

Fixed in a2f907dd

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675551261 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#discussion_r4675551261). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T04:33:36Z. **Code review location:** `tools/spirv_sampler_views.py`; line 61 ~~~~diff @@ -1,71 +1,177 @@ -"""Separate the named bindless sampler table's depth-reference uses for HLSL.""" +"""Separate the depth-reference uses of a bindless sampler table for HLSL. + +SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and +depth-reference samples needs a second view. This pass finds every uniform-constant variable whose +type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a +copy of it at descriptor set 3 and the same binding for the depth-reference uses. +""" import re +CHAINS = ("OpAccessChain", "OpInBoundsAccessChain") +BRIDGE = "%bridge_cmp" +BRIDGE_SET = "3" -def split_sampler_views(assembly): - if "Dref" not in assembly or "%samplers " not in assembly: - return assembly - lines = assembly.splitlines() - definitions = {} - comparisons = [] - ordinary = False - decorated = set() - indirect_decorations = False + +def read_module(lines): + """Collect result definitions, sample instructions and decorations from the assembly lines.""" + module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False, + "sets": {}, "bindings": {}} for index, line in enumerate(lines): words = line.split() if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]): - indirect_decorations = True - if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"): - decorated.add(words[1]) - if len(words) < 4 or words[1] != "=": + module["indirect"] = True + if words[:1] == ["OpDecorate"] and len(words) >= 3: + if words[2] == "DescriptorSet": + module["sets"].setdefault(words[1], []).append(words[3:]) + elif words[2] == "Binding": + module["bindings"].setdefault(words[1], []).append(words[3:]) + else: + module["decorated"].add(words[1]) + if len(words) < 3 or words[1] != "=": continue - definitions[words[0]] = words[2:] + module["defs"][words[0]] = words[2:] if words[2].startswith("OpImage") and "Dref" in words[2]: - comparisons.append((index, words)) - elif words[2].startswith(("OpImageSample", "OpImageGather")): - ordinary = True - if not comparisons or not ordinary: + module["comparisons"].append((index, words)) + elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")): + module["ordinary"].append(words) + return module + + +def pointee(defs, variable): + """The type a uniform-constant variable points to, or None.""" + declaration = defs.get(variable, []) + if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant": + return None + pointer = defs.get(declaration[1], []) + if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]: + return None + return pointer[2] + + +def sampler_variables(defs): + """Return the sampler tables and the plain sampler variables, in declaration order.""" + tables, plains = [], set() + for name in defs: + target = pointee(defs, name) + if target is None: + continue + shape = defs.get(target, []) + if shape == ["OpTypeSampler"]: + plains.add(name) + elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]: ~~~~ --- Fixed in a2f907dd
chatgpt-codex-connector[bot commented 2026-11-24 06:50:41 +00:00 (Migrated from github.com)

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

Code review location: tools/spirv_sampler_views.py; line 132

@@ -1,71 +1,203 @@
-"""Separate the named bindless sampler table's depth-reference uses for HLSL."""
+"""Separate the depth-reference uses of a bindless sampler table for HLSL.
+
+SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and
+depth-reference samples needs a second view. This pass finds every uniform-constant variable whose
+type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a
+copy of it at descriptor set 3 and the same binding for the depth-reference uses.
+"""
 import re
 
+CHAINS = ("OpAccessChain", "OpInBoundsAccessChain")
+BRIDGE = "%bridge_cmp"
+BRIDGE_SET = "3"
 
-def split_sampler_views(assembly):
-    if "Dref" not in assembly or "%samplers " not in assembly:
-        return assembly
-    lines = assembly.splitlines()
-    definitions = {}
-    comparisons = []
-    ordinary = False
-    decorated = set()
-    indirect_decorations = False
+
+def strip_comment(line):
+    """Drop a trailing `;` comment, leaving any `;` inside a quoted string alone."""
+    quoted = escaped = False
+    for position, char in enumerate(line):
+        if quoted and escaped:
+            escaped = False
+        elif quoted and char == "\\":
+            escaped = True
+        elif char == '"':
+            quoted = not quoted
+        elif char == ";" and not quoted:
+            return line[:position].rstrip()
+    return line
+
+
+def read_module(lines):
+    """Collect result definitions, sample instructions and decorations from the assembly lines."""
+    module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False,
+              "sets": {}, "bindings": {}}
     for index, line in enumerate(lines):
         words = line.split()
         if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]):
-            indirect_decorations = True
-        if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"):
-            decorated.add(words[1])
-        if len(words) < 4 or words[1] != "=":
+            module["indirect"] = True
+        if words[:1] == ["OpDecorate"] and len(words) >= 3:
+            if words[2] == "DescriptorSet":
+                module["sets"].setdefault(words[1], []).append(words[3:])
+            elif words[2] == "Binding":
+                module["bindings"].setdefault(words[1], []).append(words[3:])
+            else:
+                module["decorated"].add(words[1])
+        if len(words) < 3 or words[1] != "=":
             continue
-        definitions[words[0]] = words[2:]
+        module["defs"][words[0]] = words[2:]
         if words[2].startswith("OpImage") and "Dref" in words[2]:
-            comparisons.append((index, words))
-        elif words[2].startswith(("OpImageSample", "OpImageGather")):
-            ordinary = True
-    if not comparisons or not ordinary:
+            module["comparisons"].append((index, words))
+        elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")):
+            module["ordinary"].append(words)
+    return module
+
+
+def pointee(defs, variable):
+    """The type a uniform-constant variable points to, or None."""
+    declaration = defs.get(variable, [])
+    if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant":
+        return None
+    pointer = defs.get(declaration[1], [])
+    if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]:
+        return None
+    return pointer[2]
+
+
+def sampler_variables(defs):
+    """Return the sampler tables and the plain sampler variables, in declaration order."""
+    tables, plains = [], set()
+    for name in defs:
+        target = pointee(defs, name)
+        if target is None:
+            continue
+        shape = defs.get(target, [])
+        if shape == ["OpTypeSampler"]:
+            plains.add(name)
+        elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]:
+            tables.append(name)
+    return tables, plains
+
+
+def sampler_source(defs, tables, plains, sampled):
+    """Follow a sampled image to its sampler: ("table", chain, load, image) or (kind, ...) otherwise."""
+    image = defs.get(sampled, [])
+    if len(image) != 4 or image[0] != "OpSampledImage":
+        return ("image",)
+    load = defs.get(image[3], [])
+    if len(load) != 3 or load[0] != "OpLoad" or defs.get(load[1]) != ["OpTypeSampler"]:
+        return ("load",)
+    if load[2] in plains:
+        return ("plain",)
+    chain = defs.get(load[2], [])
+    if (len(chain) == 4 and chain[0] in CHAINS and chain[2] in tables
+            and defs.get(chain[1]) == ["OpTypePointer", "UniformConstant", load[1]]):
+        return ("table", chain, load, image, image[3], load[2])
+    return ("provenance",)
+
+
+FAILURES = {"image": "unsupported depth-reference sampled image",
+            "load": "unsupported depth-reference sampler load",
+            "provenance": "unsupported depth-reference sampler provenance"}
+
+
+def tables_to_split(module, tables, plains):
+    """Tables used by a depth-reference sample and by an ordinary one; also the resolved comparisons."""
+    defs = module["defs"]
+    ordinary, unresolved = set(), False
+    for words in module["ordinary"]:
+        source = sampler_source(defs, tables, plains, words[4])
+        if source[0] == "table":
+            ordinary.add(source[1][2])
+        elif source[0] != "plain":
+            unresolved = True  # an ordinary sample with an unknown sampler may use any table
+    resolved = []
+    for index, words in module["comparisons"]:
+        source = sampler_source(defs, tables, plains, words[4])
+        if source[0] == "table":
+            resolved.append((index, words, source))
+        elif source[0] != "plain":
+            raise ValueError(FAILURES[source[0]])
+    return resolved, ordinary, unresolved
+
+
+def table_slot(module, table):
+    """The (set, binding) of a table; it must carry exactly one of each and no other decoration."""
+    sets, bindings = module["sets"].get(table, []), module["bindings"].get(table, [])
+    if len(sets) != 1 or len(bindings) != 1 or len(sets[0]) != 1 or len(bindings[0]) != 1:
+        raise ValueError("sampler table requires one DescriptorSet and one Binding decoration")
+    if not (sets[0][0].isdigit() and bindings[0][0].isdigit()):
+        raise ValueError("sampler table requires literal DescriptorSet and Binding numbers")
+    if table in module["decorated"] or len(module["defs"][table]) != 3:
+        raise ValueError("unsupported sampler table declaration")
+    return sets[0][0], bindings[0][0]

P2 Badge Reject the reserved descriptor set after parsing table decorations

If the existing fixture's table decoration is changed to OpDecorate %samplers DescriptorSet 3 (with valid extra whitespace), this accepts set 3 while the reserved-set regex in split_sampler_views() misses it because it requires single spaces. The generalized path then emits both %samplers and %bridge_cmp at set 3/binding 1, so the ordinary and comparison views occupy the same sampler registers and cannot be bound independently. The parent rejected this input through its hard-coded set-0 check. Validate the parsed descriptor-set value before allocating the comparison view rather than relying on the formatting-sensitive scan.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675591746 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#discussion_r4675591746). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T04:40:24Z. **Code review location:** `tools/spirv_sampler_views.py`; line 132 ~~~~diff @@ -1,71 +1,203 @@ -"""Separate the named bindless sampler table's depth-reference uses for HLSL.""" +"""Separate the depth-reference uses of a bindless sampler table for HLSL. + +SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and +depth-reference samples needs a second view. This pass finds every uniform-constant variable whose +type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a +copy of it at descriptor set 3 and the same binding for the depth-reference uses. +""" import re +CHAINS = ("OpAccessChain", "OpInBoundsAccessChain") +BRIDGE = "%bridge_cmp" +BRIDGE_SET = "3" -def split_sampler_views(assembly): - if "Dref" not in assembly or "%samplers " not in assembly: - return assembly - lines = assembly.splitlines() - definitions = {} - comparisons = [] - ordinary = False - decorated = set() - indirect_decorations = False + +def strip_comment(line): + """Drop a trailing `;` comment, leaving any `;` inside a quoted string alone.""" + quoted = escaped = False + for position, char in enumerate(line): + if quoted and escaped: + escaped = False + elif quoted and char == "\\": + escaped = True + elif char == '"': + quoted = not quoted + elif char == ";" and not quoted: + return line[:position].rstrip() + return line + + +def read_module(lines): + """Collect result definitions, sample instructions and decorations from the assembly lines.""" + module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False, + "sets": {}, "bindings": {}} for index, line in enumerate(lines): words = line.split() if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]): - indirect_decorations = True - if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"): - decorated.add(words[1]) - if len(words) < 4 or words[1] != "=": + module["indirect"] = True + if words[:1] == ["OpDecorate"] and len(words) >= 3: + if words[2] == "DescriptorSet": + module["sets"].setdefault(words[1], []).append(words[3:]) + elif words[2] == "Binding": + module["bindings"].setdefault(words[1], []).append(words[3:]) + else: + module["decorated"].add(words[1]) + if len(words) < 3 or words[1] != "=": continue - definitions[words[0]] = words[2:] + module["defs"][words[0]] = words[2:] if words[2].startswith("OpImage") and "Dref" in words[2]: - comparisons.append((index, words)) - elif words[2].startswith(("OpImageSample", "OpImageGather")): - ordinary = True - if not comparisons or not ordinary: + module["comparisons"].append((index, words)) + elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")): + module["ordinary"].append(words) + return module + + +def pointee(defs, variable): + """The type a uniform-constant variable points to, or None.""" + declaration = defs.get(variable, []) + if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant": + return None + pointer = defs.get(declaration[1], []) + if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]: + return None + return pointer[2] + + +def sampler_variables(defs): + """Return the sampler tables and the plain sampler variables, in declaration order.""" + tables, plains = [], set() + for name in defs: + target = pointee(defs, name) + if target is None: + continue + shape = defs.get(target, []) + if shape == ["OpTypeSampler"]: + plains.add(name) + elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]: + tables.append(name) + return tables, plains + + +def sampler_source(defs, tables, plains, sampled): + """Follow a sampled image to its sampler: ("table", chain, load, image) or (kind, ...) otherwise.""" + image = defs.get(sampled, []) + if len(image) != 4 or image[0] != "OpSampledImage": + return ("image",) + load = defs.get(image[3], []) + if len(load) != 3 or load[0] != "OpLoad" or defs.get(load[1]) != ["OpTypeSampler"]: + return ("load",) + if load[2] in plains: + return ("plain",) + chain = defs.get(load[2], []) + if (len(chain) == 4 and chain[0] in CHAINS and chain[2] in tables + and defs.get(chain[1]) == ["OpTypePointer", "UniformConstant", load[1]]): + return ("table", chain, load, image, image[3], load[2]) + return ("provenance",) + + +FAILURES = {"image": "unsupported depth-reference sampled image", + "load": "unsupported depth-reference sampler load", + "provenance": "unsupported depth-reference sampler provenance"} + + +def tables_to_split(module, tables, plains): + """Tables used by a depth-reference sample and by an ordinary one; also the resolved comparisons.""" + defs = module["defs"] + ordinary, unresolved = set(), False + for words in module["ordinary"]: + source = sampler_source(defs, tables, plains, words[4]) + if source[0] == "table": + ordinary.add(source[1][2]) + elif source[0] != "plain": + unresolved = True # an ordinary sample with an unknown sampler may use any table + resolved = [] + for index, words in module["comparisons"]: + source = sampler_source(defs, tables, plains, words[4]) + if source[0] == "table": + resolved.append((index, words, source)) + elif source[0] != "plain": + raise ValueError(FAILURES[source[0]]) + return resolved, ordinary, unresolved + + +def table_slot(module, table): + """The (set, binding) of a table; it must carry exactly one of each and no other decoration.""" + sets, bindings = module["sets"].get(table, []), module["bindings"].get(table, []) + if len(sets) != 1 or len(bindings) != 1 or len(sets[0]) != 1 or len(bindings[0]) != 1: + raise ValueError("sampler table requires one DescriptorSet and one Binding decoration") + if not (sets[0][0].isdigit() and bindings[0][0].isdigit()): + raise ValueError("sampler table requires literal DescriptorSet and Binding numbers") + if table in module["decorated"] or len(module["defs"][table]) != 3: + raise ValueError("unsupported sampler table declaration") + return sets[0][0], bindings[0][0] ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Reject the reserved descriptor set after parsing table decorations** If the existing fixture's table decoration is changed to `OpDecorate %samplers DescriptorSet 3` (with valid extra whitespace), this accepts set 3 while the reserved-set regex in `split_sampler_views()` misses it because it requires single spaces. The generalized path then emits both `%samplers` and `%bridge_cmp` at set 3/binding 1, so the ordinary and comparison views occupy the same sampler registers and cannot be bound independently. The parent rejected this input through its hard-coded set-0 check. Validate the parsed descriptor-set value before allocating the comparison view rather than relying on the formatting-sensitive scan. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
tedin7 commented 2026-11-24 06:50:41 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T04:41:14Z.

Code review location: tools/spirv_sampler_views.py; line 132

@@ -1,71 +1,203 @@
-"""Separate the named bindless sampler table's depth-reference uses for HLSL."""
+"""Separate the depth-reference uses of a bindless sampler table for HLSL.
+
+SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and
+depth-reference samples needs a second view. This pass finds every uniform-constant variable whose
+type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a
+copy of it at descriptor set 3 and the same binding for the depth-reference uses.
+"""
 import re
 
+CHAINS = ("OpAccessChain", "OpInBoundsAccessChain")
+BRIDGE = "%bridge_cmp"
+BRIDGE_SET = "3"
 
-def split_sampler_views(assembly):
-    if "Dref" not in assembly or "%samplers " not in assembly:
-        return assembly
-    lines = assembly.splitlines()
-    definitions = {}
-    comparisons = []
-    ordinary = False
-    decorated = set()
-    indirect_decorations = False
+
+def strip_comment(line):
+    """Drop a trailing `;` comment, leaving any `;` inside a quoted string alone."""
+    quoted = escaped = False
+    for position, char in enumerate(line):
+        if quoted and escaped:
+            escaped = False
+        elif quoted and char == "\\":
+            escaped = True
+        elif char == '"':
+            quoted = not quoted
+        elif char == ";" and not quoted:
+            return line[:position].rstrip()
+    return line
+
+
+def read_module(lines):
+    """Collect result definitions, sample instructions and decorations from the assembly lines."""
+    module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False,
+              "sets": {}, "bindings": {}}
     for index, line in enumerate(lines):
         words = line.split()
         if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]):
-            indirect_decorations = True
-        if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"):
-            decorated.add(words[1])
-        if len(words) < 4 or words[1] != "=":
+            module["indirect"] = True
+        if words[:1] == ["OpDecorate"] and len(words) >= 3:
+            if words[2] == "DescriptorSet":
+                module["sets"].setdefault(words[1], []).append(words[3:])
+            elif words[2] == "Binding":
+                module["bindings"].setdefault(words[1], []).append(words[3:])
+            else:
+                module["decorated"].add(words[1])
+        if len(words) < 3 or words[1] != "=":
             continue
-        definitions[words[0]] = words[2:]
+        module["defs"][words[0]] = words[2:]
         if words[2].startswith("OpImage") and "Dref" in words[2]:
-            comparisons.append((index, words))
-        elif words[2].startswith(("OpImageSample", "OpImageGather")):
-            ordinary = True
-    if not comparisons or not ordinary:
+            module["comparisons"].append((index, words))
+        elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")):
+            module["ordinary"].append(words)
+    return module
+
+
+def pointee(defs, variable):
+    """The type a uniform-constant variable points to, or None."""
+    declaration = defs.get(variable, [])
+    if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant":
+        return None
+    pointer = defs.get(declaration[1], [])
+    if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]:
+        return None
+    return pointer[2]
+
+
+def sampler_variables(defs):
+    """Return the sampler tables and the plain sampler variables, in declaration order."""
+    tables, plains = [], set()
+    for name in defs:
+        target = pointee(defs, name)
+        if target is None:
+            continue
+        shape = defs.get(target, [])
+        if shape == ["OpTypeSampler"]:
+            plains.add(name)
+        elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]:
+            tables.append(name)
+    return tables, plains
+
+
+def sampler_source(defs, tables, plains, sampled):
+    """Follow a sampled image to its sampler: ("table", chain, load, image) or (kind, ...) otherwise."""
+    image = defs.get(sampled, [])
+    if len(image) != 4 or image[0] != "OpSampledImage":
+        return ("image",)
+    load = defs.get(image[3], [])
+    if len(load) != 3 or load[0] != "OpLoad" or defs.get(load[1]) != ["OpTypeSampler"]:
+        return ("load",)
+    if load[2] in plains:
+        return ("plain",)
+    chain = defs.get(load[2], [])
+    if (len(chain) == 4 and chain[0] in CHAINS and chain[2] in tables
+            and defs.get(chain[1]) == ["OpTypePointer", "UniformConstant", load[1]]):
+        return ("table", chain, load, image, image[3], load[2])
+    return ("provenance",)
+
+
+FAILURES = {"image": "unsupported depth-reference sampled image",
+            "load": "unsupported depth-reference sampler load",
+            "provenance": "unsupported depth-reference sampler provenance"}
+
+
+def tables_to_split(module, tables, plains):
+    """Tables used by a depth-reference sample and by an ordinary one; also the resolved comparisons."""
+    defs = module["defs"]
+    ordinary, unresolved = set(), False
+    for words in module["ordinary"]:
+        source = sampler_source(defs, tables, plains, words[4])
+        if source[0] == "table":
+            ordinary.add(source[1][2])
+        elif source[0] != "plain":
+            unresolved = True  # an ordinary sample with an unknown sampler may use any table
+    resolved = []
+    for index, words in module["comparisons"]:
+        source = sampler_source(defs, tables, plains, words[4])
+        if source[0] == "table":
+            resolved.append((index, words, source))
+        elif source[0] != "plain":
+            raise ValueError(FAILURES[source[0]])
+    return resolved, ordinary, unresolved
+
+
+def table_slot(module, table):
+    """The (set, binding) of a table; it must carry exactly one of each and no other decoration."""
+    sets, bindings = module["sets"].get(table, []), module["bindings"].get(table, [])
+    if len(sets) != 1 or len(bindings) != 1 or len(sets[0]) != 1 or len(bindings[0]) != 1:
+        raise ValueError("sampler table requires one DescriptorSet and one Binding decoration")
+    if not (sets[0][0].isdigit() and bindings[0][0].isdigit()):
+        raise ValueError("sampler table requires literal DescriptorSet and Binding numbers")
+    if table in module["decorated"] or len(module["defs"][table]) != 3:
+        raise ValueError("unsupported sampler table declaration")
+    return sets[0][0], bindings[0][0]

Fixed in 828a0723

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675596644 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#discussion_r4675596644). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T04:41:14Z. **Code review location:** `tools/spirv_sampler_views.py`; line 132 ~~~~diff @@ -1,71 +1,203 @@ -"""Separate the named bindless sampler table's depth-reference uses for HLSL.""" +"""Separate the depth-reference uses of a bindless sampler table for HLSL. + +SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and +depth-reference samples needs a second view. This pass finds every uniform-constant variable whose +type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a +copy of it at descriptor set 3 and the same binding for the depth-reference uses. +""" import re +CHAINS = ("OpAccessChain", "OpInBoundsAccessChain") +BRIDGE = "%bridge_cmp" +BRIDGE_SET = "3" -def split_sampler_views(assembly): - if "Dref" not in assembly or "%samplers " not in assembly: - return assembly - lines = assembly.splitlines() - definitions = {} - comparisons = [] - ordinary = False - decorated = set() - indirect_decorations = False + +def strip_comment(line): + """Drop a trailing `;` comment, leaving any `;` inside a quoted string alone.""" + quoted = escaped = False + for position, char in enumerate(line): + if quoted and escaped: + escaped = False + elif quoted and char == "\\": + escaped = True + elif char == '"': + quoted = not quoted + elif char == ";" and not quoted: + return line[:position].rstrip() + return line + + +def read_module(lines): + """Collect result definitions, sample instructions and decorations from the assembly lines.""" + module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False, + "sets": {}, "bindings": {}} for index, line in enumerate(lines): words = line.split() if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]): - indirect_decorations = True - if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"): - decorated.add(words[1]) - if len(words) < 4 or words[1] != "=": + module["indirect"] = True + if words[:1] == ["OpDecorate"] and len(words) >= 3: + if words[2] == "DescriptorSet": + module["sets"].setdefault(words[1], []).append(words[3:]) + elif words[2] == "Binding": + module["bindings"].setdefault(words[1], []).append(words[3:]) + else: + module["decorated"].add(words[1]) + if len(words) < 3 or words[1] != "=": continue - definitions[words[0]] = words[2:] + module["defs"][words[0]] = words[2:] if words[2].startswith("OpImage") and "Dref" in words[2]: - comparisons.append((index, words)) - elif words[2].startswith(("OpImageSample", "OpImageGather")): - ordinary = True - if not comparisons or not ordinary: + module["comparisons"].append((index, words)) + elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")): + module["ordinary"].append(words) + return module + + +def pointee(defs, variable): + """The type a uniform-constant variable points to, or None.""" + declaration = defs.get(variable, []) + if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant": + return None + pointer = defs.get(declaration[1], []) + if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]: + return None + return pointer[2] + + +def sampler_variables(defs): + """Return the sampler tables and the plain sampler variables, in declaration order.""" + tables, plains = [], set() + for name in defs: + target = pointee(defs, name) + if target is None: + continue + shape = defs.get(target, []) + if shape == ["OpTypeSampler"]: + plains.add(name) + elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]: + tables.append(name) + return tables, plains + + +def sampler_source(defs, tables, plains, sampled): + """Follow a sampled image to its sampler: ("table", chain, load, image) or (kind, ...) otherwise.""" + image = defs.get(sampled, []) + if len(image) != 4 or image[0] != "OpSampledImage": + return ("image",) + load = defs.get(image[3], []) + if len(load) != 3 or load[0] != "OpLoad" or defs.get(load[1]) != ["OpTypeSampler"]: + return ("load",) + if load[2] in plains: + return ("plain",) + chain = defs.get(load[2], []) + if (len(chain) == 4 and chain[0] in CHAINS and chain[2] in tables + and defs.get(chain[1]) == ["OpTypePointer", "UniformConstant", load[1]]): + return ("table", chain, load, image, image[3], load[2]) + return ("provenance",) + + +FAILURES = {"image": "unsupported depth-reference sampled image", + "load": "unsupported depth-reference sampler load", + "provenance": "unsupported depth-reference sampler provenance"} + + +def tables_to_split(module, tables, plains): + """Tables used by a depth-reference sample and by an ordinary one; also the resolved comparisons.""" + defs = module["defs"] + ordinary, unresolved = set(), False + for words in module["ordinary"]: + source = sampler_source(defs, tables, plains, words[4]) + if source[0] == "table": + ordinary.add(source[1][2]) + elif source[0] != "plain": + unresolved = True # an ordinary sample with an unknown sampler may use any table + resolved = [] + for index, words in module["comparisons"]: + source = sampler_source(defs, tables, plains, words[4]) + if source[0] == "table": + resolved.append((index, words, source)) + elif source[0] != "plain": + raise ValueError(FAILURES[source[0]]) + return resolved, ordinary, unresolved + + +def table_slot(module, table): + """The (set, binding) of a table; it must carry exactly one of each and no other decoration.""" + sets, bindings = module["sets"].get(table, []), module["bindings"].get(table, []) + if len(sets) != 1 or len(bindings) != 1 or len(sets[0]) != 1 or len(bindings[0]) != 1: + raise ValueError("sampler table requires one DescriptorSet and one Binding decoration") + if not (sets[0][0].isdigit() and bindings[0][0].isdigit()): + raise ValueError("sampler table requires literal DescriptorSet and Binding numbers") + if table in module["decorated"] or len(module["defs"][table]) != 3: + raise ValueError("unsupported sampler table declaration") + return sets[0][0], bindings[0][0] ~~~~ --- Fixed in 828a0723
chatgpt-codex-connector[bot commented 2026-11-24 06:50:41 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-24T04:53:28Z.

Code review location: tools/spirv_sampler_views.py; line 160

@@ -1,71 +1,204 @@
-"""Separate the named bindless sampler table's depth-reference uses for HLSL."""
-import re
+"""Separate the depth-reference uses of a bindless sampler table for HLSL.
 
+SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and
+depth-reference samples needs a second view. This pass finds every uniform-constant variable whose
+type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a
+copy of it at descriptor set 3 and the same binding for the depth-reference uses.
+"""
 
-def split_sampler_views(assembly):
-    if "Dref" not in assembly or "%samplers " not in assembly:
-        return assembly
-    lines = assembly.splitlines()
-    definitions = {}
-    comparisons = []
-    ordinary = False
-    decorated = set()
-    indirect_decorations = False
+CHAINS = ("OpAccessChain", "OpInBoundsAccessChain")
+BRIDGE = "%bridge_cmp"
+BRIDGE_SET = "3"
+
+
+def strip_comment(line):
+    """Drop a trailing `;` comment, leaving any `;` inside a quoted string alone."""
+    quoted = escaped = False
+    for position, char in enumerate(line):
+        if quoted and escaped:
+            escaped = False
+        elif quoted and char == "\\":
+            escaped = True
+        elif char == '"':
+            quoted = not quoted
+        elif char == ";" and not quoted:
+            return line[:position].rstrip()
+    return line
+
+
+def read_module(lines):
+    """Collect result definitions, sample instructions and decorations from the assembly lines."""
+    module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False,
+              "sets": {}, "bindings": {}}
     for index, line in enumerate(lines):
         words = line.split()
         if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]):
-            indirect_decorations = True
-        if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"):
-            decorated.add(words[1])
-        if len(words) < 4 or words[1] != "=":
+            module["indirect"] = True
+        if words[:1] == ["OpDecorate"] and len(words) >= 3:
+            if words[2] == "DescriptorSet":
+                module["sets"].setdefault(words[1], []).append(words[3:])
+            elif words[2] == "Binding":
+                module["bindings"].setdefault(words[1], []).append(words[3:])
+            else:
+                module["decorated"].add(words[1])
+        if len(words) < 3 or words[1] != "=":
             continue
-        definitions[words[0]] = words[2:]
+        module["defs"][words[0]] = words[2:]
         if words[2].startswith("OpImage") and "Dref" in words[2]:
-            comparisons.append((index, words))
-        elif words[2].startswith(("OpImageSample", "OpImageGather")):
-            ordinary = True
-    if not comparisons or not ordinary:
+            module["comparisons"].append((index, words))
+        elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")):
+            module["ordinary"].append(words)
+    return module
+
+
+def pointee(defs, variable):
+    """The type a uniform-constant variable points to, or None."""
+    declaration = defs.get(variable, [])
+    if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant":
+        return None
+    pointer = defs.get(declaration[1], [])
+    if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]:
+        return None
+    return pointer[2]
+
+
+def sampler_variables(defs):
+    """Return the sampler tables and the plain sampler variables, in declaration order."""
+    tables, plains = [], set()
+    for name in defs:
+        target = pointee(defs, name)
+        if target is None:
+            continue
+        shape = defs.get(target, [])
+        if shape == ["OpTypeSampler"]:
+            plains.add(name)
+        elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]:
+            tables.append(name)
+    return tables, plains
+
+
+def sampler_source(defs, tables, plains, sampled):
+    """Follow a sampled image to its sampler: ("table", chain, load, image) or (kind, ...) otherwise."""
+    image = defs.get(sampled, [])
+    if len(image) != 4 or image[0] != "OpSampledImage":
+        return ("image",)
+    load = defs.get(image[3], [])
+    if len(load) != 3 or load[0] != "OpLoad" or defs.get(load[1]) != ["OpTypeSampler"]:
+        return ("load",)
+    if load[2] in plains:
+        return ("plain",)
+    chain = defs.get(load[2], [])
+    if (len(chain) == 4 and chain[0] in CHAINS and chain[2] in tables
+            and defs.get(chain[1]) == ["OpTypePointer", "UniformConstant", load[1]]):
+        return ("table", chain, load, image, image[3], load[2])
+    return ("provenance",)
+
+
+FAILURES = {"image": "unsupported depth-reference sampled image",
+            "load": "unsupported depth-reference sampler load",
+            "provenance": "unsupported depth-reference sampler provenance"}
+
+
+def tables_to_split(module, tables, plains):
+    """Tables used by a depth-reference sample and by an ordinary one; also the resolved comparisons."""
+    defs = module["defs"]
+    ordinary, unresolved = set(), False
+    for words in module["ordinary"]:
+        source = sampler_source(defs, tables, plains, words[4])
+        if source[0] == "table":
+            ordinary.add(source[1][2])
+        elif source[0] != "plain":
+            unresolved = True  # an ordinary sample with an unknown sampler may use any table
+    resolved = []
+    for index, words in module["comparisons"]:
+        source = sampler_source(defs, tables, plains, words[4])
+        if source[0] == "table":
+            resolved.append((index, words, source))
+        elif source[0] != "plain":
+            raise ValueError(FAILURES[source[0]])
+    return resolved, ordinary, unresolved
+
+
+def table_slot(module, table):
+    """The (set, binding) of a table; it must carry exactly one of each and no other decoration."""
+    sets, bindings = module["sets"].get(table, []), module["bindings"].get(table, [])
+    if len(sets) != 1 or len(bindings) != 1 or len(sets[0]) != 1 or len(bindings[0]) != 1:
+        raise ValueError("sampler table requires one DescriptorSet and one Binding decoration")
+    if not (sets[0][0].isdigit() and bindings[0][0].isdigit()):
+        raise ValueError("sampler table requires literal DescriptorSet and Binding numbers")
+    if table in module["decorated"] or len(module["defs"][table]) != 3:
+        raise ValueError("unsupported sampler table declaration")
+    return sets[0][0], bindings[0][0]
+
+
+def register_end(defs, table, binding):
+    """The first register after a table's views; a runtime or unresolvable size has no end."""
+    shape = defs[defs[defs[table][1]][2]]
+    length = defs.get(shape[2], []) if shape[0] == "OpTypeArray" else []
+    if len(length) == 3 and length[0] == "OpConstant" and length[2].isdigit() and int(length[2]) > 0:
+        return int(binding) + int(length[2])
+    return None
+
+
+def bridge_names(module, split):
+    """Name one bridge variable per split table; the first keeps the plain prefix."""
+    names, ranges = {}, []
+    for number, table in enumerate(split):
+        _, binding = table_slot(module, table)
+        end = register_end(module["defs"], table, binding)
+        for other, start, stop in ranges:
+            if (stop is None or int(binding) < stop) and (end is None or start < end):
+                raise ValueError(f"sampler tables {other} and {table} overlap in the set 3 register range")
+        ranges.append((table, int(binding), end))
+        names[table] = BRIDGE if number == 0 else f"{BRIDGE}_table_{number}"
+    return names
+
+
+def split_sampler_views(assembly):
+    if "Dref" not in assembly:
+        return assembly
+    lines = [strip_comment(line) for line in assembly.splitlines()]

P2 Badge Preserve quote state across lines when stripping comments

For a mixed-sampler module containing a valid multiline OpSource string, each call to strip_comment() forgets whether the previous line opened a quote. A continuation line such as int tmp = 0; }" is consequently truncated at the semicolon, removing the string's closing quote and producing an unassemblable rewritten module. Adding that source string to the existing sampler fixture reproduces the corruption, while the parent preserves the string. Preserve quote and escape state across the full assembly rather than resetting it for every line.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675670974 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#discussion_r4675670974). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-24T04:53:28Z. **Code review location:** `tools/spirv_sampler_views.py`; line 160 ~~~~diff @@ -1,71 +1,204 @@ -"""Separate the named bindless sampler table's depth-reference uses for HLSL.""" -import re +"""Separate the depth-reference uses of a bindless sampler table for HLSL. +SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and +depth-reference samples needs a second view. This pass finds every uniform-constant variable whose +type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a +copy of it at descriptor set 3 and the same binding for the depth-reference uses. +""" -def split_sampler_views(assembly): - if "Dref" not in assembly or "%samplers " not in assembly: - return assembly - lines = assembly.splitlines() - definitions = {} - comparisons = [] - ordinary = False - decorated = set() - indirect_decorations = False +CHAINS = ("OpAccessChain", "OpInBoundsAccessChain") +BRIDGE = "%bridge_cmp" +BRIDGE_SET = "3" + + +def strip_comment(line): + """Drop a trailing `;` comment, leaving any `;` inside a quoted string alone.""" + quoted = escaped = False + for position, char in enumerate(line): + if quoted and escaped: + escaped = False + elif quoted and char == "\\": + escaped = True + elif char == '"': + quoted = not quoted + elif char == ";" and not quoted: + return line[:position].rstrip() + return line + + +def read_module(lines): + """Collect result definitions, sample instructions and decorations from the assembly lines.""" + module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False, + "sets": {}, "bindings": {}} for index, line in enumerate(lines): words = line.split() if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]): - indirect_decorations = True - if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"): - decorated.add(words[1]) - if len(words) < 4 or words[1] != "=": + module["indirect"] = True + if words[:1] == ["OpDecorate"] and len(words) >= 3: + if words[2] == "DescriptorSet": + module["sets"].setdefault(words[1], []).append(words[3:]) + elif words[2] == "Binding": + module["bindings"].setdefault(words[1], []).append(words[3:]) + else: + module["decorated"].add(words[1]) + if len(words) < 3 or words[1] != "=": continue - definitions[words[0]] = words[2:] + module["defs"][words[0]] = words[2:] if words[2].startswith("OpImage") and "Dref" in words[2]: - comparisons.append((index, words)) - elif words[2].startswith(("OpImageSample", "OpImageGather")): - ordinary = True - if not comparisons or not ordinary: + module["comparisons"].append((index, words)) + elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")): + module["ordinary"].append(words) + return module + + +def pointee(defs, variable): + """The type a uniform-constant variable points to, or None.""" + declaration = defs.get(variable, []) + if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant": + return None + pointer = defs.get(declaration[1], []) + if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]: + return None + return pointer[2] + + +def sampler_variables(defs): + """Return the sampler tables and the plain sampler variables, in declaration order.""" + tables, plains = [], set() + for name in defs: + target = pointee(defs, name) + if target is None: + continue + shape = defs.get(target, []) + if shape == ["OpTypeSampler"]: + plains.add(name) + elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]: + tables.append(name) + return tables, plains + + +def sampler_source(defs, tables, plains, sampled): + """Follow a sampled image to its sampler: ("table", chain, load, image) or (kind, ...) otherwise.""" + image = defs.get(sampled, []) + if len(image) != 4 or image[0] != "OpSampledImage": + return ("image",) + load = defs.get(image[3], []) + if len(load) != 3 or load[0] != "OpLoad" or defs.get(load[1]) != ["OpTypeSampler"]: + return ("load",) + if load[2] in plains: + return ("plain",) + chain = defs.get(load[2], []) + if (len(chain) == 4 and chain[0] in CHAINS and chain[2] in tables + and defs.get(chain[1]) == ["OpTypePointer", "UniformConstant", load[1]]): + return ("table", chain, load, image, image[3], load[2]) + return ("provenance",) + + +FAILURES = {"image": "unsupported depth-reference sampled image", + "load": "unsupported depth-reference sampler load", + "provenance": "unsupported depth-reference sampler provenance"} + + +def tables_to_split(module, tables, plains): + """Tables used by a depth-reference sample and by an ordinary one; also the resolved comparisons.""" + defs = module["defs"] + ordinary, unresolved = set(), False + for words in module["ordinary"]: + source = sampler_source(defs, tables, plains, words[4]) + if source[0] == "table": + ordinary.add(source[1][2]) + elif source[0] != "plain": + unresolved = True # an ordinary sample with an unknown sampler may use any table + resolved = [] + for index, words in module["comparisons"]: + source = sampler_source(defs, tables, plains, words[4]) + if source[0] == "table": + resolved.append((index, words, source)) + elif source[0] != "plain": + raise ValueError(FAILURES[source[0]]) + return resolved, ordinary, unresolved + + +def table_slot(module, table): + """The (set, binding) of a table; it must carry exactly one of each and no other decoration.""" + sets, bindings = module["sets"].get(table, []), module["bindings"].get(table, []) + if len(sets) != 1 or len(bindings) != 1 or len(sets[0]) != 1 or len(bindings[0]) != 1: + raise ValueError("sampler table requires one DescriptorSet and one Binding decoration") + if not (sets[0][0].isdigit() and bindings[0][0].isdigit()): + raise ValueError("sampler table requires literal DescriptorSet and Binding numbers") + if table in module["decorated"] or len(module["defs"][table]) != 3: + raise ValueError("unsupported sampler table declaration") + return sets[0][0], bindings[0][0] + + +def register_end(defs, table, binding): + """The first register after a table's views; a runtime or unresolvable size has no end.""" + shape = defs[defs[defs[table][1]][2]] + length = defs.get(shape[2], []) if shape[0] == "OpTypeArray" else [] + if len(length) == 3 and length[0] == "OpConstant" and length[2].isdigit() and int(length[2]) > 0: + return int(binding) + int(length[2]) + return None + + +def bridge_names(module, split): + """Name one bridge variable per split table; the first keeps the plain prefix.""" + names, ranges = {}, [] + for number, table in enumerate(split): + _, binding = table_slot(module, table) + end = register_end(module["defs"], table, binding) + for other, start, stop in ranges: + if (stop is None or int(binding) < stop) and (end is None or start < end): + raise ValueError(f"sampler tables {other} and {table} overlap in the set 3 register range") + ranges.append((table, int(binding), end)) + names[table] = BRIDGE if number == 0 else f"{BRIDGE}_table_{number}" + return names + + +def split_sampler_views(assembly): + if "Dref" not in assembly: + return assembly + lines = [strip_comment(line) for line in assembly.splitlines()] ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Preserve quote state across lines when stripping comments** For a mixed-sampler module containing a valid multiline `OpSource` string, each call to `strip_comment()` forgets whether the previous line opened a quote. A continuation line such as `int tmp = 0; }"` is consequently truncated at the semicolon, removing the string's closing quote and producing an unassemblable rewritten module. Adding that source string to the existing sampler fixture reproduces the corruption, while the parent preserves the string. Preserve quote and escape state across the full assembly rather than resetting it for every line. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
tedin7 commented 2026-11-24 06:50:42 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-24T04:54:11Z.

Code review location: tools/spirv_sampler_views.py; line 160

@@ -1,71 +1,204 @@
-"""Separate the named bindless sampler table's depth-reference uses for HLSL."""
-import re
+"""Separate the depth-reference uses of a bindless sampler table for HLSL.
 
+SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and
+depth-reference samples needs a second view. This pass finds every uniform-constant variable whose
+type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a
+copy of it at descriptor set 3 and the same binding for the depth-reference uses.
+"""
 
-def split_sampler_views(assembly):
-    if "Dref" not in assembly or "%samplers " not in assembly:
-        return assembly
-    lines = assembly.splitlines()
-    definitions = {}
-    comparisons = []
-    ordinary = False
-    decorated = set()
-    indirect_decorations = False
+CHAINS = ("OpAccessChain", "OpInBoundsAccessChain")
+BRIDGE = "%bridge_cmp"
+BRIDGE_SET = "3"
+
+
+def strip_comment(line):
+    """Drop a trailing `;` comment, leaving any `;` inside a quoted string alone."""
+    quoted = escaped = False
+    for position, char in enumerate(line):
+        if quoted and escaped:
+            escaped = False
+        elif quoted and char == "\\":
+            escaped = True
+        elif char == '"':
+            quoted = not quoted
+        elif char == ";" and not quoted:
+            return line[:position].rstrip()
+    return line
+
+
+def read_module(lines):
+    """Collect result definitions, sample instructions and decorations from the assembly lines."""
+    module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False,
+              "sets": {}, "bindings": {}}
     for index, line in enumerate(lines):
         words = line.split()
         if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]):
-            indirect_decorations = True
-        if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"):
-            decorated.add(words[1])
-        if len(words) < 4 or words[1] != "=":
+            module["indirect"] = True
+        if words[:1] == ["OpDecorate"] and len(words) >= 3:
+            if words[2] == "DescriptorSet":
+                module["sets"].setdefault(words[1], []).append(words[3:])
+            elif words[2] == "Binding":
+                module["bindings"].setdefault(words[1], []).append(words[3:])
+            else:
+                module["decorated"].add(words[1])
+        if len(words) < 3 or words[1] != "=":
             continue
-        definitions[words[0]] = words[2:]
+        module["defs"][words[0]] = words[2:]
         if words[2].startswith("OpImage") and "Dref" in words[2]:
-            comparisons.append((index, words))
-        elif words[2].startswith(("OpImageSample", "OpImageGather")):
-            ordinary = True
-    if not comparisons or not ordinary:
+            module["comparisons"].append((index, words))
+        elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")):
+            module["ordinary"].append(words)
+    return module
+
+
+def pointee(defs, variable):
+    """The type a uniform-constant variable points to, or None."""
+    declaration = defs.get(variable, [])
+    if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant":
+        return None
+    pointer = defs.get(declaration[1], [])
+    if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]:
+        return None
+    return pointer[2]
+
+
+def sampler_variables(defs):
+    """Return the sampler tables and the plain sampler variables, in declaration order."""
+    tables, plains = [], set()
+    for name in defs:
+        target = pointee(defs, name)
+        if target is None:
+            continue
+        shape = defs.get(target, [])
+        if shape == ["OpTypeSampler"]:
+            plains.add(name)
+        elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]:
+            tables.append(name)
+    return tables, plains
+
+
+def sampler_source(defs, tables, plains, sampled):
+    """Follow a sampled image to its sampler: ("table", chain, load, image) or (kind, ...) otherwise."""
+    image = defs.get(sampled, [])
+    if len(image) != 4 or image[0] != "OpSampledImage":
+        return ("image",)
+    load = defs.get(image[3], [])
+    if len(load) != 3 or load[0] != "OpLoad" or defs.get(load[1]) != ["OpTypeSampler"]:
+        return ("load",)
+    if load[2] in plains:
+        return ("plain",)
+    chain = defs.get(load[2], [])
+    if (len(chain) == 4 and chain[0] in CHAINS and chain[2] in tables
+            and defs.get(chain[1]) == ["OpTypePointer", "UniformConstant", load[1]]):
+        return ("table", chain, load, image, image[3], load[2])
+    return ("provenance",)
+
+
+FAILURES = {"image": "unsupported depth-reference sampled image",
+            "load": "unsupported depth-reference sampler load",
+            "provenance": "unsupported depth-reference sampler provenance"}
+
+
+def tables_to_split(module, tables, plains):
+    """Tables used by a depth-reference sample and by an ordinary one; also the resolved comparisons."""
+    defs = module["defs"]
+    ordinary, unresolved = set(), False
+    for words in module["ordinary"]:
+        source = sampler_source(defs, tables, plains, words[4])
+        if source[0] == "table":
+            ordinary.add(source[1][2])
+        elif source[0] != "plain":
+            unresolved = True  # an ordinary sample with an unknown sampler may use any table
+    resolved = []
+    for index, words in module["comparisons"]:
+        source = sampler_source(defs, tables, plains, words[4])
+        if source[0] == "table":
+            resolved.append((index, words, source))
+        elif source[0] != "plain":
+            raise ValueError(FAILURES[source[0]])
+    return resolved, ordinary, unresolved
+
+
+def table_slot(module, table):
+    """The (set, binding) of a table; it must carry exactly one of each and no other decoration."""
+    sets, bindings = module["sets"].get(table, []), module["bindings"].get(table, [])
+    if len(sets) != 1 or len(bindings) != 1 or len(sets[0]) != 1 or len(bindings[0]) != 1:
+        raise ValueError("sampler table requires one DescriptorSet and one Binding decoration")
+    if not (sets[0][0].isdigit() and bindings[0][0].isdigit()):
+        raise ValueError("sampler table requires literal DescriptorSet and Binding numbers")
+    if table in module["decorated"] or len(module["defs"][table]) != 3:
+        raise ValueError("unsupported sampler table declaration")
+    return sets[0][0], bindings[0][0]
+
+
+def register_end(defs, table, binding):
+    """The first register after a table's views; a runtime or unresolvable size has no end."""
+    shape = defs[defs[defs[table][1]][2]]
+    length = defs.get(shape[2], []) if shape[0] == "OpTypeArray" else []
+    if len(length) == 3 and length[0] == "OpConstant" and length[2].isdigit() and int(length[2]) > 0:
+        return int(binding) + int(length[2])
+    return None
+
+
+def bridge_names(module, split):
+    """Name one bridge variable per split table; the first keeps the plain prefix."""
+    names, ranges = {}, []
+    for number, table in enumerate(split):
+        _, binding = table_slot(module, table)
+        end = register_end(module["defs"], table, binding)
+        for other, start, stop in ranges:
+            if (stop is None or int(binding) < stop) and (end is None or start < end):
+                raise ValueError(f"sampler tables {other} and {table} overlap in the set 3 register range")
+        ranges.append((table, int(binding), end))
+        names[table] = BRIDGE if number == 0 else f"{BRIDGE}_table_{number}"
+    return names
+
+
+def split_sampler_views(assembly):
+    if "Dref" not in assembly:
+        return assembly
+    lines = [strip_comment(line) for line in assembly.splitlines()]

Fixed in 0806ef57

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4675675145 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/1224#discussion_r4675675145). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-24T04:54:11Z. **Code review location:** `tools/spirv_sampler_views.py`; line 160 ~~~~diff @@ -1,71 +1,204 @@ -"""Separate the named bindless sampler table's depth-reference uses for HLSL.""" -import re +"""Separate the depth-reference uses of a bindless sampler table for HLSL. +SPIRV-Cross gives a sampler table one HLSL type, so a table that serves both ordinary and +depth-reference samples needs a second view. This pass finds every uniform-constant variable whose +type is an array (fixed or runtime) of samplers, whatever its names and decorations, and adds a +copy of it at descriptor set 3 and the same binding for the depth-reference uses. +""" -def split_sampler_views(assembly): - if "Dref" not in assembly or "%samplers " not in assembly: - return assembly - lines = assembly.splitlines() - definitions = {} - comparisons = [] - ordinary = False - decorated = set() - indirect_decorations = False +CHAINS = ("OpAccessChain", "OpInBoundsAccessChain") +BRIDGE = "%bridge_cmp" +BRIDGE_SET = "3" + + +def strip_comment(line): + """Drop a trailing `;` comment, leaving any `;` inside a quoted string alone.""" + quoted = escaped = False + for position, char in enumerate(line): + if quoted and escaped: + escaped = False + elif quoted and char == "\\": + escaped = True + elif char == '"': + quoted = not quoted + elif char == ";" and not quoted: + return line[:position].rstrip() + return line + + +def read_module(lines): + """Collect result definitions, sample instructions and decorations from the assembly lines.""" + module = {"defs": {}, "comparisons": [], "ordinary": [], "decorated": set(), "indirect": False, + "sets": {}, "bindings": {}} for index, line in enumerate(lines): words = line.split() if words[:1] in (["OpGroupDecorate"], ["OpDecorateId"]): - indirect_decorations = True - if words[:1] == ["OpDecorate"] and len(words) >= 3 and words[2] not in ("Binding", "DescriptorSet"): - decorated.add(words[1]) - if len(words) < 4 or words[1] != "=": + module["indirect"] = True + if words[:1] == ["OpDecorate"] and len(words) >= 3: + if words[2] == "DescriptorSet": + module["sets"].setdefault(words[1], []).append(words[3:]) + elif words[2] == "Binding": + module["bindings"].setdefault(words[1], []).append(words[3:]) + else: + module["decorated"].add(words[1]) + if len(words) < 3 or words[1] != "=": continue - definitions[words[0]] = words[2:] + module["defs"][words[0]] = words[2:] if words[2].startswith("OpImage") and "Dref" in words[2]: - comparisons.append((index, words)) - elif words[2].startswith(("OpImageSample", "OpImageGather")): - ordinary = True - if not comparisons or not ordinary: + module["comparisons"].append((index, words)) + elif words[2].startswith(("OpImageSample", "OpImageGather", "OpImageSparseSample", "OpImageSparseGather")): + module["ordinary"].append(words) + return module + + +def pointee(defs, variable): + """The type a uniform-constant variable points to, or None.""" + declaration = defs.get(variable, []) + if len(declaration) < 3 or declaration[0] != "OpVariable" or declaration[2] != "UniformConstant": + return None + pointer = defs.get(declaration[1], []) + if len(pointer) != 3 or pointer[:2] != ["OpTypePointer", "UniformConstant"]: + return None + return pointer[2] + + +def sampler_variables(defs): + """Return the sampler tables and the plain sampler variables, in declaration order.""" + tables, plains = [], set() + for name in defs: + target = pointee(defs, name) + if target is None: + continue + shape = defs.get(target, []) + if shape == ["OpTypeSampler"]: + plains.add(name) + elif shape[:1] in (["OpTypeRuntimeArray"], ["OpTypeArray"]) and defs.get(shape[1]) == ["OpTypeSampler"]: + tables.append(name) + return tables, plains + + +def sampler_source(defs, tables, plains, sampled): + """Follow a sampled image to its sampler: ("table", chain, load, image) or (kind, ...) otherwise.""" + image = defs.get(sampled, []) + if len(image) != 4 or image[0] != "OpSampledImage": + return ("image",) + load = defs.get(image[3], []) + if len(load) != 3 or load[0] != "OpLoad" or defs.get(load[1]) != ["OpTypeSampler"]: + return ("load",) + if load[2] in plains: + return ("plain",) + chain = defs.get(load[2], []) + if (len(chain) == 4 and chain[0] in CHAINS and chain[2] in tables + and defs.get(chain[1]) == ["OpTypePointer", "UniformConstant", load[1]]): + return ("table", chain, load, image, image[3], load[2]) + return ("provenance",) + + +FAILURES = {"image": "unsupported depth-reference sampled image", + "load": "unsupported depth-reference sampler load", + "provenance": "unsupported depth-reference sampler provenance"} + + +def tables_to_split(module, tables, plains): + """Tables used by a depth-reference sample and by an ordinary one; also the resolved comparisons.""" + defs = module["defs"] + ordinary, unresolved = set(), False + for words in module["ordinary"]: + source = sampler_source(defs, tables, plains, words[4]) + if source[0] == "table": + ordinary.add(source[1][2]) + elif source[0] != "plain": + unresolved = True # an ordinary sample with an unknown sampler may use any table + resolved = [] + for index, words in module["comparisons"]: + source = sampler_source(defs, tables, plains, words[4]) + if source[0] == "table": + resolved.append((index, words, source)) + elif source[0] != "plain": + raise ValueError(FAILURES[source[0]]) + return resolved, ordinary, unresolved + + +def table_slot(module, table): + """The (set, binding) of a table; it must carry exactly one of each and no other decoration.""" + sets, bindings = module["sets"].get(table, []), module["bindings"].get(table, []) + if len(sets) != 1 or len(bindings) != 1 or len(sets[0]) != 1 or len(bindings[0]) != 1: + raise ValueError("sampler table requires one DescriptorSet and one Binding decoration") + if not (sets[0][0].isdigit() and bindings[0][0].isdigit()): + raise ValueError("sampler table requires literal DescriptorSet and Binding numbers") + if table in module["decorated"] or len(module["defs"][table]) != 3: + raise ValueError("unsupported sampler table declaration") + return sets[0][0], bindings[0][0] + + +def register_end(defs, table, binding): + """The first register after a table's views; a runtime or unresolvable size has no end.""" + shape = defs[defs[defs[table][1]][2]] + length = defs.get(shape[2], []) if shape[0] == "OpTypeArray" else [] + if len(length) == 3 and length[0] == "OpConstant" and length[2].isdigit() and int(length[2]) > 0: + return int(binding) + int(length[2]) + return None + + +def bridge_names(module, split): + """Name one bridge variable per split table; the first keeps the plain prefix.""" + names, ranges = {}, [] + for number, table in enumerate(split): + _, binding = table_slot(module, table) + end = register_end(module["defs"], table, binding) + for other, start, stop in ranges: + if (stop is None or int(binding) < stop) and (end is None or start < end): + raise ValueError(f"sampler tables {other} and {table} overlap in the set 3 register range") + ranges.append((table, int(binding), end)) + names[table] = BRIDGE if number == 0 else f"{BRIDGE}_table_{number}" + return names + + +def split_sampler_views(assembly): + if "Dref" not in assembly: + return assembly + lines = [strip_comment(line) for line in assembly.splitlines()] ~~~~ --- Fixed in 0806ef57
upstream-sync closed this pull request 2026-11-24 08:01:19 +00:00
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!1217
No description provided.