Skip to content

Shaders: lower image_gather4_c_lz and image_gather4_c_lz_o (MIMG 0x4f, 0x5f) - #1489

Open
AscilCH wants to merge 1 commit into
Marvisak:mainfrom
AscilCH:fix/image-gather4-cmp-lz
Open

AscilCH wants to merge 1 commit into
Marvisak:mainfrom
AscilCH:fix/image-gather4-cmp-lz

Conversation

@AscilCH

@AscilCH AscilCH commented Nov 24, 2026

Copy link
Copy Markdown

Summary

Lower GFX10 comparison gather instructions image_gather4_c_lz (MIMG 0x4f) and image_gather4_c_lz_o (MIMG 0x5f) in Lower::image() (crates/victory-shader/src/emit/lower.rs) to DXIL dx.op.textureGatherCmp.f32 (opcode 74).

(Complementary to #383 and #694, which do not cover comparison gather instructions.)

Reproduction (Before Fix)

Lowering a synthetic compute shader using image_gather4_c_lz failed with:

lower: Unsupported { offset: 52, what: "image_gather4_c_lz" }

Implementation

  • Map "image_gather4_c_lz" | "image_gather4_c_lz_o" to DXIL opcode 74 (textureGatherCmp.f32), setting cmp = matches!(op, 64 | 65 | 74) so the sampler handle is annotated as a comparison sampler (0x8000) and first accounts for both optional _o offset word and comparison reference value.
  • Emit dx.op.textureGatherCmp.f32 passing the comparison reference from addr_val(self, first - 1) as f32, and unpack all four gathered comparison results (matches!(op, 73 | 74)).
  • Guard against unsupported forms rather than silently miscompiling:
    • Reject 1D/3D dimensions (!matches!(kind, 2 | 5 | 7)).
    • Reject cube gathers with programmable offsets (offset_word && kind == 5).
    • Reject non-red comparison gathers (op == 74 && *dmask != 1), since D3D12 hardware and WARP ignore channel != 0 on textureGatherCmp and always compare channel 0.

Test

Added synthetic end-to-end test emit::valu_tests::image_gather4_c_lz_and_offset_match_rdna2:

  • Hardware GPU + WARP + dxil.dll validation for 2D image_gather4_c_lz across multiple comparison thresholds verifying all 4 bilinear footprint slots.
  • Hardware GPU + WARP + dxil.dll validation for 2D image_gather4_c_lz_o with both positive and negative 6-bit sign-extended programmable offsets (-1, +1) and (+1, -1).
  • dxil.dll validation for Cube (dim = 3) image_gather4_c_lz.
  • Clean rejection checks for non-red dmask = 0x2, cube _o, and 1D gather.

Verification

  • rustfmt --edition 2024 --check crates/victory-shader/src/emit/valu_tests.rs and modified lines of lower.rs: clean
  • cargo test -p victory-shader --locked image_gather4_c_lz_and_offset_match_rdna2 (hardware + WARP + dxil.dll): passed
  • VICTORY_WARP=1 cargo test -p victory-shader --locked -- --test-threads=1: 121 passed, 0 failed
  • cargo xtask policy: 154 files ok
  • cargo clippy --workspace --all-targets --locked -- -D warnings: clean
  • cargo clippy --workspace --all-targets --all-features --locked -- -D warnings: clean

…, 0x5f)

Lower GFX10 comparison gather instructions `image_gather4_c_lz` (0x4f) and
`image_gather4_c_lz_o` (0x5f) in `Lower::image` to DXIL
`dx.op.textureGatherCmp.f32` (opcode 74):

- Bind a comparison sampler (`0x8000`) and pass the reference value from
  address slot `first - 1` (slot 0 without `_o`, slot 1 after the packed
  offset word with `_o`).
- Unpack all four comparison results from `ResRet.f32`, matching
  `image_gather4_lz`.
- Reject non-2D/2DArray/Cube dimensions, cube gathers with programmable
  offsets, and non-red comparison gathers (`dmask != 1`, since D3D12
  comparison gather only compares channel 0).

Add `emit::valu_tests::image_gather4_c_lz_and_offset_match_rdna2` testing
2D `image_gather4_c_lz` and `image_gather4_c_lz_o` (positive and negative
6-bit signed offsets) on hardware GPU + WARP + `dxil.dll`, Cube DXIL
validation, and clean rejection of unsupported forms.

@DenRakEiw DenRakEiw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested locally merged onto origin/main (Windows 11 x64, NVIDIA GeForce RTX 5090 + WARP, Rust 1.98.1 MSVC):

  • cargo clippy -p victory-shader --all-targets — 0 warnings
  • cargo xtask policy — ok
  • Test failure on BOTH RTX 5090 hardware and WARP: cargo test -p victory-shader --lib image_gather4_c_lz_and_offset_match_rdna2 fails at crates/victory-shader/src/emit/valu_tests.rs:1184:17:
assertion `left == right` failed: hardware: constants=[
    0x40f00000,
    0x3f000000,
    0x3f000000,
    0x00000000,
]
  left: [9.0, 10.0, 6.0, 5.0]
 right: [1.0, 1.0, 0.0, 0.0]

Both hardware (RTX 5090) and WARP return the raw gathered texel values ([9.0, 10.0, 6.0, 5.0]) instead of the comparison results ([1.0, 1.0, 0.0, 0.0] against ref = 7.5), which suggests the comparison gather is either executing as a non-comparison gather or not binding/honoring the comparison sampler in the lowered DXIL / host dispatch. Holding off approval until the test passes on hardware and WARP.

AI-assisted (Gemini 4 Neon).

@matheusfermiano-source

Copy link
Copy Markdown

A note for anyone running this on Linux: under Proton, image_gather4_c_lz_and_offset_match_rdna2 fails on both of my GPUs. The cause is the test's texture, not the lowering.

Head e0a052c, first case (constants=[0x40f00000, 0x3f000000, 0x3f000000, 0]), want [1.0, 1.0, 0.0, 0.0]:

GPU (vkd3d-proton) got
Radeon 660M, RADV Mesa 26.3.1 (3.1.0 and 3.2.0) [0.0, 0.0, 0.0, 0.0]
RTX 3050 Laptop, NVIDIA 620.73.04 (3.1.0) [9.0, 10.0, 6.0, 5.0], the raw texels with no comparison

The test gathers from an RGBA32F color texture (View::Texture) through a comparison sampler. On both drivers, vulkaninfo --show-formats lists FORMAT_FEATURE_2_SAMPLED_IMAGE_DEPTH_COMPARISON_BIT only for depth formats, not for R32G32B32A32_SFLOAT or R32_SFLOAT. So vkd3d-proton has no supported way to honor the comparison on that texture, and each driver does something different.

The rest of the suite on the Radeon: 119 passed, and the only other failure is emit::tests::stub_pipeline_is_created, as on main (vkd3d-proton accepts a zeroed DXIL hash; see #1218). Nothing that passes on main fails.

If the test host had a depth resource read as R32_FLOAT (the way shadow maps are usually bound), the test would probably run under Proton too. I have not tried that.

Built on Linux with llvm-mingw for x86_64-pc-windows-gnullvm (Rust 1.98.1); dxil.dll from DXC 1.9.2609 was loaded. Synthetic tests only, no game files. AI-assisted (Claude Code, Opus 5.5); every run was on this machine.

@catminou4 catminou4 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tested locally on macOS arm64 (rustc 1.98.1): PR head merged cleanly into current main (ffe310e), cargo test -p victory-shader --locked → 96 passed, 0 failed. Execution/valu tests are #[cfg(all(test, windows))] and were not run here; lowering/structure coverage only.

image_gather4_c_lz/_o (MIMG 0x4f/0x5f) → textureGatherCmp.f32 (op 74) looks right:

  • comparison reference taken from addr_val(first - 1) like image_sample_c, and cmp set extended to op 74 so the sampler is keyed as a comparison sampler;
  • conservative guards: 1D/3D kinds rejected, cube + texel offsets rejected, dmask != 1 rejected for the comparison gather (D3D12 compares channel 0 only);
  • gather result channels [0,1,2,3] like the plain gather.

The valu test covers both _lz and _o plus the offset form on hardware and WARP — please confirm it passes on Windows before merge.

@Comtesse1

Copy link
Copy Markdown

Native Windows readback: all six comparison gathers match with an R32_FLOAT fixture

On PR head e0a052c, I tested the same six synthetic cases on an RTX 3080 (driver 621.01, Windows 11 build 26300) and separately on Microsoft WARP. On both devices, D3D12 reports ordinary gather but not comparison gather for the original R32G32B32A32_FLOAT format. I skipped that unsupported configuration rather than treating its output as a reference.

I kept the PR's shaders, comparison sampler, coordinates, thresholds, offsets, and expected vectors unchanged. The test-only change uploads the same red texels to a typed R32_FLOAT texture with a matching SRV, which both devices report supports comparison gather. All 6/6 cases (24/24 returned components) matched on each device, in each of two independent processes. For the first case (reference 7.5), both returned [1, 1, 0, 0]. The offset cases passed too.

I would change the test fixture before diagnosing a lowering bug from the four-channel result. This is native D3D12 only: no Proton, Xbox, game, full suite, or depth-stencil rendering test. The attachment includes the test-only patch, per-case readbacks, format-query source and reproduction commands.

AI use: OpenAI Codex (GPT-5.5) prepared the instrumentation and report and ran the tests on this machine.

VIctory-1489-RTX3080-readbacks.zip

@wwwwwwww3333333

Copy link
Copy Markdown
Contributor

A third driver for the same failure: RX 6750 XT (RDNA2, gfx1031), AMD driver 32.0.21045.29003, i5-13400F, Windows 11, Rust 1.98.1 MSVC. Head e0a052c on main ffe310e (clean merge). Native D3D12, no Proton.

image_gather4_c_lz_and_offset_match_rdna2 fails on the hardware adapter at the first case: constants [0x40f00000, 0x3f000000, 0x3f000000, 0], got [0.0, 0.0, 0.0, 0.0], want [1.0, 1.0, 0.0, 0.0]. The rest of victory-shader passes: 120 passed, 1 failed.

So with the RGBA32F View::Texture fixture, the results are:

Two different answers across three drivers for one input, which is what an unsupported comparison-gather format looks like rather than a lowering bug. It agrees with @Comtesse1's finding that every case matches once the fixture is a typed R32_FLOAT texture. I haven't run that patch on AMD.

Synthetic tests only, no game files. AI-assisted (Claude picked the PRs and wrote the batch script; I ran it on my machine).

@steven-seagull27

steven-seagull27 commented Nov 24, 2026 •

Copy link
Copy Markdown

I tested the depth-texture suggestion on PR head e0a052c under native Windows 11 (build 26300.10075, NVIDIA driver 32.0.16.2124, Rust 1.98.1 MSVC). All six comparison-gather cases passed on the RTX 5080 with the depth texture. On this machine WARP passed all six with either texture.

D3D12 adapter Original RGBA32F color texture Depth texture with R32_FLOAT SRV
NVIDIA GeForce RTX 5080 0/6 6/6
Microsoft Basic Render Driver (WARP) 6/6 6/6

At UV (0.5, 0.5) with reference 7.5, the RTX 5080 returned the raw texels [9, 10, 6, 5] from the color texture and the expected [1, 1, 0, 0] from the depth texture. I recorded each adapter’s identity and readbacks independently for the three ordinary gathers and three offset cases. The emitted shaders passed DXIL validation with SDK 10.0.26100.0.

The patch adds a depth-capable R32_TYPELESS resource to the test host, exposes it through an R32_FLOAT SRV, and seeds it with the original red-channel values. Both runs used the same shader, sampler, thresholds and offsets. Download the patch · View the diff

From the PR checkout, after downloading depth-texture.patch:

git apply --check depth-texture.patch
git apply depth-texture.patch
cargo test -p victory-shader --lib --locked emit::valu_tests::image_gather4_c_lz_and_offset_match_rdna2 -- --exact --nocapture

I verified the downloaded patch applies cleanly to e0a052c. With it applied, the shader library suite reported 121 passed, 0 failed and 1 ignored. Four optional compiler-comparison tests reported a skip within that pass count.

@sinan-cmyk

Copy link
Copy Markdown

The new test fails on NVIDIA (Ada) and passes on WARP

Result: image_gather4_c_lz_and_offset_match_rdna2 fails on NVIDIA and passes on WARP. I merged head e0a052c onto main ffe310e. The test fails 2 out of 2 times on the RTX 4070 SUPER and passes with VICTORY_WARP=1.

assertion `left == right` failed: hardware: constants=[...]
  left: [9.0, 10.0, 6.0, 5.0]
 right: [1.0, 1.0, 0.0, 0.0]

On NVIDIA, the gather returns the raw texel values instead of the comparison results. That suggests the host sampler bound for the test is not a comparison sampler there, or the comparison state is dropped on this path, and WARP compares anyway. Only the comparison form is affected. The rest of the suite passes.

Offline. I merged the head onto main ffe310e (clean merge) and ran victory translate --validate --list on shaders.rpf (1.0.2.1), with dxil.dll 1.8.2502.11, compared program by program (25,889 programs). Validated: 21,724 on both, 0 gained, 0 lost, no failure reason changed. That is expected for a fix whose instructions sit behind earlier failures.

Machine: RTX 4070 SUPER (Ada, 32-lane waves, driver 32.0.16.1088), the default adapter; Windows 11 25H2; Rust 1.98.1. The rest of cargo test --locked -p victory-shader --lib passes. No game data. AI-assisted (Claude Code).

@steven-seagull27

Copy link
Copy Markdown

@AscilCH I put the tested depth-texture fixture in one commit on my fork, based directly on your PR head e0a052c. With your PR branch checked out, you can apply it with:

git fetch https://github.com/steven-seagull27/VIctory.git codex/pr1489-depth
git cherry-pick bcc553ef1b4995387a002104adf5067506a19a71

I verified the cherry-pick in a clean checkout of e0a052c and reran the focused test successfully:

cargo test -p victory-shader --lib --locked emit::valu_tests::image_gather4_c_lz_and_offset_match_rdna2 -- --exact --nocapture

The change is confined to the synthetic fixture and its test host. With the depth texture, all six comparison-gather cases matched on both the RTX 5080 and WARP. Per-adapter results

@wwwwwwww3333333

Copy link
Copy Markdown
Contributor

The R32_FLOAT fixture also fixes it on AMD. RX 6750 XT (RDNA2, gfx1031, AMD driver 32.0.21045.29003), Windows 11, Rust 1.98.1 MSVC, head e0a052c on main ffe310e. In my earlier run the original RGBA32F fixture returned zeros here. With the comparison gather reading a typed R32_FLOAT texture, image_gather4_c_lz_and_offset_match_rdna2 passes on the hardware adapter and on WARP, and victory-shader passes 121/121. cargo clippy -p victory-shader --all-targets -- -D warnings is clean.

So the same fix now holds on NVIDIA (@Comtesse1, @remigiuszbyczkowski-svg), AMD and WARP. The patch I used adds a View::RedTexture to the test harness rather than a depth texture. @steven-seagull27's depth-texture commit should do the same job.

Patch I ran (test harness + the test's fixture)
--- a/crates/victory-shader/src/emit/host.rs
+++ b/crates/victory-shader/src/emit/host.rs
@@ -910,6 +910,9 @@
 pub enum View<'a> {
     /// An RGBA32F texture SRV (width, height, texels).
     Texture(u32, u32, &'a [[f32; 4]]),
+    /// An R32_FLOAT texture SRV (width, height, texels): a format that
+    /// supports comparison sampling and comparison gathers.
+    RedTexture(u32, u32, &'a [f32]),
     /// An RGBA32F cube SRV (face size, texels of faces +x -x +y -y +z -z).
     Cube(u32, &'a [[f32; 4]]),
     /// A raw buffer UAV of this many dwords, zeroed.
@@ -1152,6 +1155,56 @@
                         );
                         keep.push(tex);
                     }
+                    View::RedTexture(w, h, texels) => {
+                        let desc = texture_as(w, h, D3D12_RESOURCE_FLAG_NONE, DXGI_FORMAT_R32_FLOAT);
+                        let tex = make(
+                            D3D12_HEAP_TYPE_DEFAULT,
+                            &desc,
+                            D3D12_RESOURCE_STATE_COPY_DEST,
+                        )?;
+                        let pitch = (w as usize * 4).next_multiple_of(256);
+                        let upload = make(
+                            D3D12_HEAP_TYPE_UPLOAD,
+                            &buffer((pitch * h as usize) as u64, D3D12_RESOURCE_FLAG_NONE),
+                            D3D12_RESOURCE_STATE_GENERIC_READ,
+                        )?;
+                        let mut p = std::ptr::null_mut();
+                        upload.Map(0, None, Some(&mut p)).map_err(err)?;
+                        for y in 0..h as usize {
+                            let row = &texels[y * w as usize..(y + 1) * w as usize];
+                            std::ptr::copy_nonoverlapping(
+                                row.as_ptr().cast::<u8>(),
+                                p.cast::<u8>().add(y * pitch),
+                                row.len() * 4,
+                            );
+                        }
+                        upload.Unmap(0, None);
+                        let from = D3D12_TEXTURE_COPY_LOCATION {
+                            pResource: std::mem::transmute_copy(&upload),
+                            Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
+                            Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
+                                PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
+                                    Offset: 0,
+                                    Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
+                                        Format: DXGI_FORMAT_R32_FLOAT,
+                                        Width: w,
+                                        Height: h,
+                                        Depth: 1,
+                                        RowPitch: pitch as u32,
+                                    },
+                                },
+                            },
+                        };
+                        list.CopyTextureRegion(&subresource(&tex), 0, 0, 0, &from, None);
+                        keep.push(upload);
+                        list.ResourceBarrier(&[transition(
+                            &tex,
+                            D3D12_RESOURCE_STATE_COPY_DEST,
+                            D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE,
+                        )]);
+                        dev.CreateShaderResourceView(&tex, None, at);
+                        keep.push(tex);
+                    }
                     View::RawUav(_) | View::HalfUav(_) => {
                         // (dwords, format, elements, flags)
                         let (n, format, elements, flags) = match *v {
--- a/crates/victory-shader/src/emit/valu_tests.rs
+++ b/crates/victory-shader/src/emit/valu_tests.rs
@@ -1144,7 +1144,10 @@
         MaxLOD: f32::MAX,
         ..Default::default()
     }];
-    let views = [View::Texture(4, 4, &texels), View::RawUav(4)];
+    // Comparison gathers need a format that supports them (R32_FLOAT, not
+    // RGBA32F): on RGBA32F drivers disagree (raw texels, zeros).
+    let red: Vec<f32> = texels.iter().map(|t| t[0]).collect();
+    let views = [View::RedTexture(4, 4, &red), View::RawUav(4)];
 
     fn run_gather(
         shader: &HostShader,

Unit tests only, no game files. AI-assisted (Claude; I ran it on my machine).

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Needs rebase. This pull request conflicts with main (conflicting: crates/victory-shader/src/emit/lower.rs, crates/victory-shader/src/emit/valu_tests.rs). It will be reviewed once it is rebased onto the current main.


Generated by Claude Code

@steven-seagull27

Copy link
Copy Markdown

@AscilCH I resolved the three conflicts on your comparison-gather branch against main at 63bcca43. This tested merge commit keeps your original commit and the depth-fixture commit. The test now uses main’s shared builder/validator, which supplies the newer shader metadata.

All six depth readbacks matched on each of RTX 5080 (621.40) and Windows WARP (10.0.26100.10068), in three fresh processes. That includes both signed offsets, (-1,+1) and (+1,-1). The cube module validated. The non-red, 1D and offset-cube refusal checks passed. The separate explicit-LOD hardware test on RTX still has the same lane-0 mismatch as unchanged main; it passes on WARP on both revisions. Strict shader Clippy and asset policy passed.

With your PR branch checked out, this fast-forwards it:

git fetch https://github.com/steven-seagull27/VIctory.git codex/pr1489-current-main
git merge --ff-only FETCH_HEAD

I also tested your signed-offset fixture on #1687. Its red results agree, but its non-red masks translated and read red on both devices. A joint integration commit retains your red-only guard and fixtures alongside #1687’s additional offset sample support, with both authors’ commits in the history. This gives maintainers the option of reviewing the overlap once.

AI-assisted with Codex. All inputs were synthetic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants